php8.5
Home/ Manual/ dom / domdocument/ DOMDocument::getElementById

DOMDocument::getElementById

PHP function Edit on GitHub ✎

(PHP 5, PHP 7, PHP 8)

Searches for an element with a certain id

Description

DOMDocument::getElementById(string $elementId): DOMElement|null

This function is similar to domdocument.getelementsbytagname but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with domelement.setidattribute or a DTD which defines an attribute to be of type ID. In the latter case, you will need to validate your document with domdocument.validate or DOMDocument::$validateOnParse before using this function.

Parameters

elementId

The unique id value for an element.

Return Values

Returns the DOMElement or null if the element is not found.

Examples

DOMDocument::getElementById() Example

Example

php
<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->load('examples/book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

The above example will output:

output
The element whose id is 'php-basics' is: book 

See Also

  • DOMDocument::getElementsByTagName

Source: reference/dom/domdocument/getelementbyid.xml · from the official PHP manual (php/doc-en)