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’=’comments’. So, the result selector will be:

descendant::div[@id=’comments’ and contains(concat(‘ ‘,normalize-space(@class),’ ‘),’ comments-area ‘)]

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

(descendant::div[@id=’comments’ and contains(concat(‘ ‘,normalize-space(@class),’ ‘),’ comments-area ‘)])[0]

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

(descendant::div[@id=’comments’ and contains(concat(‘ ‘,normalize-space(@class),’ ‘),’ comments-area ‘)])[last()]

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 we can test our selectors here.

Leave a Reply