Thursday, October 23, 2025
HomeLanguagesPHP | DOMElement hasAttribute() Function

PHP | DOMElement hasAttribute() Function

The DOMElement::hasAttribute() function is an inbuilt function in PHP which is used to know whether attribute with a specific name exists as a member of the element.

Syntax:

bool DOMElement::hasAttribute( string $name )

Parameters: This function accepts a single parameter $name which holds the name of attribute.

Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the DOMElement::hasAttribute() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <div>
        <!-- id attribute is there -->
        <p id=\"prog\"> HELLO </p>
    </div>
</root>");
  
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
  
foreach ($nodeList as $node) {
    if($node->hasAttribute('id')) {
        echo "Yes, id attribute is there.";
    }
}
?>


Output:

Yes, id attribute is there.

Program 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <div>
        <!-- id attribute is missing -->
        <p> HELLO </p>
    </div>
</root>");
  
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
foreach ($nodeList as $node) {
    if(!$node->hasAttribute('id')) {
        echo "No, id attribute isn't there.";
    }
}
?>


Output:

No, id attribute isn't there.

Reference: https://www.php.net/manual/en/domelement.hasattribute.php

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

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