Search code examples
phpxpathdomxpath

can DOMXPath::query be limited to a certain depth?


Is there a way to limit the depth DOMXPath::query will look at?

Consider the following document:

<div>
    <span>
        <div>
        </div>
    </span>
</div>

How could I limit the query

//div

So it only matches the first level and not the descendants?


Solution

  • This will select the div elements that are not inside of any other div elements (similar to Gumbo's answer, but will check all levels, not just direct parent)

    //div[not(ancestor::div)]