Search code examples
phpdomxpathdomdocument

xpath to exclude elements that have a class


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.


Solution

  • 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.