Wednesday, June 17, 2026
HomeLanguagesPHP | DOMNode hasAttributes() Function

PHP | DOMNode hasAttributes() Function

The DOMNode::hasAttributes() function is an inbuilt function in PHP which is used to check if a node has attributes or not.

Syntax:

bool DOMNode::hasAttributes( void )

Parameters: This function doesn’t accept any parameters.

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

Below examples illustrate the DOMNode::hasAttributes() function in PHP:

Example 1:




<?php
   
// Create a new DOMDocument
$dom = new DOMDocument();
    
// Create a paragraph element
$element = $dom->createElement('p',
      'This is the paragraph element!');
   
// Set the attribute
$element->setAttribute('id', 'my_id');
   
// Append the child
$dom->appendChild($element);
    
// 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.

Example 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Create a paragraph element
$element = $dom->createElement('p'
         'This is the paragraph element!');
  
// Set the attribute
$element->setAttribute('class', 'my_class');
  
// Append the child
$dom->appendChild($element);
   
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
foreach ($nodeList as $node) {
    if(!$node->hasAttribute('id')) {
        echo "No, id attribute is not there.";
    }
}
?>


Output:

No, id attribute is not there.

Reference: https://www.php.net/manual/en/domnode.hasattributes.php

RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6898 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS