Mr J
Mr J

Reputation: 2973

Xpath for finding element that does not have sibling

So I'm trying to extract the a href locations from the links below but only for the a elements that do NOT have a span sibling. I've managed to figure out the Xpath for finding the ones that DO, but how do I negate this? I've tried using count() and not() but can't seem to get them to be valid or return anything.

<div class="member">
    <a href="/test1" class="ahrefclass">shouldntfindme</a>
    <span class="evilspan">evilspan</span>
</div>
<div class="member">
    <a href="/test2" class="ahrefclass">findme</a>
</div>
<div class="member">
    <a href="/test3" class="ahrefclass">shouldntfindme</a>
    <span class="evilspan">evilspan</span>
</div>
<div class="member">
    <a href="/test4" class="ahrefclass">findme</a>
</div>
<div class="member">
    <a href="/test5" class="ahrefclass">shouldntfindme</a>
    <span class="evilspan">evilspan</span>
</div>

My Xpath so far is

//a[@class="ahrefclass"][../span[@class="evilspan"]]

Upvotes: 2

Views: 2838

Answers (1)

choroba
choroba

Reputation: 242188

Just negate the condition:

//a[@class="ahrefclass"][not(../span[@class="evilspan"])]

which is, in this case, equivalent to

//a[@class="ahrefclass" and not(../span[@class="evilspan"])]

Upvotes: 10

Related Questions