xpath to exclude elements that have a class

sameold picture sameold · Jun 20, 2012 · Viewed 9.2k times · Source

I'm trying to select all dom elements that have id="mydiv" but exclude the ones that also have the class="exclass". Right now I'm doing the first part //*[@id="mydiv"]. How do I add the class exclusion part?

P.S. In case you're wondering why I need to select multiple elements that have the same id, I'm just working on an existing DOM that I can't control.

Answer

Ja͢ck picture Ja͢ck · Jun 20, 2012

You can use negation:

//*[@id="mydiv" and @class!="exclass"]

If the class attribute may not exist on all nodes, you need this:

//*[@id="mydiv" and (not(@class) or @class!="exclass")]

The last (somewhat) odd logic can be turned into what Michael proposed:

//*[@id="mydiv" and not(@class="exclass")]

Though, personally, the fact that XPath cannot make comparisons if the attribute is missing feels a bit like a shortcoming.