1

Trying to create a XPath to find input elements with a specific label on my website. However I want it to not be found if its ancestor is a specific div.

Assume we got the following HTML:

<div class="content"> <div class="abc"> <div> //some other elements </div> <div> <h2>Name</h2> <input></input> </div> </div> <div> <div> //some other elements </div> <div> <h2>Name</h2> <input></input> </div> </div> </div> 

I only want to find the name input in the div that does not have the surrounding div "abc".

I have this that only finds the name input if it's in the the abc wrapper but can't make it find the other way around:

//div[contains(@class, 'content')]//div[contains(@class, 'abc')]//descendant::h2[.='Name']/following-sibling::input 

I thought I could use a not() function around the contains(abc) like so:

[not(contains(@class, 'abc'))] 

But it did not work.

1 Answer 1

3

This XPath will select all h2 elements whose string value equals "Name" and that is not a descendent of a div with of class = 'abc':

//h2[.='Name' and not(ancestor::div/@class = 'abc')] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thnaks man it worked, I just have a question regarding this part ´div/@class = 'abc'´ am I understanding this wrong or does that not mean a div with a child that has the class 'abc' instead of the div itself?
No, not(ancestor::div/@class = 'abc') returns true when there are no ancestor div elements with class attributes equal to abc. It could also be written as not(ancestor::div[@class = 'abc']).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.