Friday, October 24, 2025
HomeLanguagesPHP | DOMDocument getElementById() Function

PHP | DOMDocument getElementById() Function

The DOMDocument::getElementById() function is an inbuilt function in PHP which is used to search for an element with a certain id.

Syntax:

DOMElement DOMDocument::getElementById( string $elementId )

Parameters:This function accepts a single parameter $elementId which holds the id to search for.

Return Value: This function returns the DOMElement or NULL if the element is not found.

Below given programs illustrate the DOMDocument::getElementById() function in PHP:

Program 1: In this program we will get the tagname of element with certain id.




<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Enable validate on parse
$dom->validateOnParse = true;
  
// Create a div element
$element = $dom->appendChild(new DOMElement('div'));
  
// Create a id attribute to div
$attr = $element->setAttributeNode(
        new DOMAttr('id', 'my_id'));
  
// Set that attribute as id
$element->setIDAttribute('id', true);
  
// Get the tag name
$tagname = $dom->getElementById('my_id')->tagName;
  
echo $tagname;
?>


Output:

div // Because id 'my_id' is applied to div tag.

Program 2: In this program we will get the content of element with certain id.




<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Enable validate on parse
$dom->validateOnParse = true;
  
// Create a div element
$element = $dom->appendChild(new DOMElement('div',
   'Hey, this is the text content of the div element.'));
  
// Create a id attribute to div
$attr = $element->setAttributeNode(
          new DOMAttr('id', 'my_id'));
  
// Set that attribute as id
$element->setIDAttribute('id', true);
  
// Get the tag content
$tagcontent = $dom->getElementById('my_id')->textContent;
  
echo $tagcontent;
?>


Output:

Hey, this is the text content of the div element.

Reference: https://www.php.net/manual/en/domdocument.getelementbyid.php

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS