Friday, October 24, 2025
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
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