XPath: Search for HTML element within HTML element

Viewed 60

With XPath, how would you search for elements that only contain another specific element? For example, what expression would result in getting all <p> tags that contain <strong> elements within them?

<p>This is some text that <strong>contains another HTML element</strong></p>
2 Answers

In XPath you use square brackets to filter. It is called the predicate. See I.e. this tutorial .

To select all p’s with a element strong you use

 //p[strong]

If you want to find all p’s with only the element strong and no other elements, you add

//p[strong][count(*)=count(strong)]

The * stands for any element.

If, as in your example , you only interested in p’s with the strong element being the last child node you use

//p[strong[not(following-sibling::node())]]

Predicates are the way to go.

what expression would result in getting all p tags that contain elements within them?

If you only want to select p elements with direct strong children, you can use p[strong], if you're looking for any descendants, use p[descendant::strong]. In both cases the context node has to be at the level of the p elements.

Related