tags:

views:

166

answers:

5

Is it possible to select an h1 tag that does not contain any img tags with a single line XPath expression? If so, what is it?

+2  A: 
//h1[count(img) = 0]

I assume this is for XHTML, otherwise no XPath.

xcut
This works if the img tag is a direct child of <h1>. Is it possible to check if there is no img tag at any level within the h1 tag?
Pheter
+3  A: 

You can use the not() function:

//h1[not(descendant::img)]
Lukáš Lalinský
This appears to be the cleanest solution, but it will not check if an img tag exists that is a child of a child of an h1 tag. Is it possible to check recursively through each child of the h1 tag and their children to ensure that there is no img tag?
Pheter
Well, the `not()` argument is also just a XPath, you can use anything there. Updated the answer.
Lukáš Lalinský
Thanks, your updated solution is just what I was looking for but Andrew Arnott beat you to it :P
Pheter
A: 

//h1[count(img) = 0]

runrunraygun
+6  A: 

Use the not operator and the descendent axis to catch h1 tags without even a distant img child.

//h1[not(descendant::img)]
Andrew Arnott
A: 

To find an h1 element with no img child:

//h1[not(img)]

To find an h1 element with no img descendant:

//h1[not(.//img)]

or

//h1[not(descendant::img)]

which might be easier to understand when reading your code.

Robert Rossney