BenMorel
BenMorel

Reputation: 36524

How to search by id under a given element?

How can I search a DOMElement by id, that appears under another DOMElement?

$element->ownerDocument->getElementById('my-id');

...will search the whole document. I only want the element to be returned if it appears under $element.

Upvotes: 0

Views: 98

Answers (2)

hakre
hakre

Reputation: 197952

You can do so with XPath. The following will have the that element (the typical less than 120 chars one-liner):

$idElement = ($r = simplexml_import_dom($element)->xpath('.//*[@id="my-id"]')) 
             ? dom_import_simplexml($r[0]) : NULL;

If it's not found, you will get NULL. What this basically does is using the short-hand form what @ircmaxell suggested in his answer:

descendant::*[@id="my-id"]
.//*[@id="my-id"]

The context-node is the same, in simplexml xpath, it's automatically to the context-node, in DOMXPath you need to specify it.

oh just seeing, it's you who edited the xpath in that answer, so the important part is when bound to the context-node, to use the dot . before the double slashes // as the slash otherwise will go to the root again, the dot prevents this (compare with specifying a relative file-path in your file-system).

See as well: php - context node in xpath problem

Upvotes: 1

ircmaxell
ircmaxell

Reputation: 165201

Quite simple with XPath:

$xpath = new DomXpath($element->ownerDocument);
$subelement = $xpath->query('descendant::*[@id="my-id"]', $element);

Basically, it looks for an element anywhere in the tree below the context node ($element here) with the id attribute equal to my-id...

Upvotes: 4

Related Questions