XPath elements selectorAccelerator for WordPress

An XPath selector is a powerful language to choose the specified set from the tags tree.

While developing this product we wanted to use CSS selectors that simpler and more often use. But CSS doesn’t allow to choose the item by index. Therefore, we decided to use XPath.

E.g. we want to get all div tags that contain comments-area in their class attribute and have id that equals to comments. So, the result selector will be:

.//div[@id='comments' and contains(concat(' ',normalize-space(@class),' '),' comments-area ')]

To get only first element from that set we should type:

(.//div[@id='comments' and contains(concat(' ',normalize-space(@class),' '),' comments-area ')])[0]

To get only last element from that set we should type:

(.//div[@id='comments' and contains(concat(' ',normalize-space(@class),' '),' comments-area ')])[last()]

To get all element from that set after the 2nd one:

(.//div[@id='comments' and contains(concat(' ',normalize-space(@class),' '),' comments-area ')])[position()>2]

If you familiar with CSS selectors it can be converted to XPath by this service.

The samples above show the most used cases while setting up the product. More information about Xpath syntax can be found here and here. And we can test the selectors on a real markup.

Leave a Reply