Friday, September 5, 2025
HomeLanguagesPHP | DOMNodeList count() Function

PHP | DOMNodeList count() Function

The DOMNodeList::count() function is an inbuilt function in PHP which is used to get the number of nodes in the list.

Syntax:

int DOMNodeList::count( void )

Parameters: This function doesn’t accept any parameter.

Return Value: This function returns the number of nodes in the list.

Below examples illustrate the DOMNodeList::count() function in PHP:

Example 1:




<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a div element
$element = $document->appendChild(new DOMElement('div'));
  
// Create a h1 element
$text1 = new DOMElement('h1', 'neveropen');
  
// Create another h1 elements
$text2 = new DOMElement('h1', 'Another neveropen');
  
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
  
// Get all elements with tag name 'h1'
$elements = $document->getElementsByTagName('h1');
  
// Count the elements
echo $elements->count();
?>


Output:

2

Example 2:




<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a div element
$element = $document->appendChild(new DOMElement('div'));
  
// Create a h1 element
$text1 = new DOMElement('h1', 'neveropen');
  
// Create another h1 elements
$text2 = new DOMElement('h1', 'Another neveropen');
  
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
  
// Get all elements with tag name 'h1'
$elements = $document->getElementsByTagName('h1');
   
// Count the elements
echo 'Before removing: ';
echo $elements->count() . "<br>";
  
// Remove  a child
$element->removeChild($text2);
  
// Get all elements with tag name 'h1'
$elements = $document->getElementsByTagName('h1');
   
// Count the elements
echo 'After removing: ';
echo $elements->count();
?>


Output:

Before removing: 2
After removing: 1

Reference: https://www.php.net/manual/en/domnodelist.count.php

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS