js count element tags

JS Count Element Tags

Counting element tags in HTML documents is an essential task for web developers. It helps to keep track of the number of times a particular tag appears in a web page. In this article, we will discuss multiple ways to count HTML element tags using JavaScript.

Method 1: Using getElementsByTagName() method

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name. We can use this method to count the number of times a specific tag appears in the HTML document.

const numberOfElements = document.getElementsByTagName('div').length;
console.log(`Number of <div> tags: ${numberOfElements}`);

In the above code, we are using the getElementsByTagName() method to get all the <div> tags in the document and then counting their length.

Method 2: Using querySelectorAll() method

We can also use the querySelectorAll() method to select all elements that match a specific CSS selector. This method returns a NodeList object that contains all matching elements.

const numberOfElements = document.querySelectorAll('div').length;
console.log(`Number of <div> tags: ${numberOfElements}`);

In the above code, we are using the querySelectorAll() method to select all <div> tags in the document and then counting their length.

Method 3: Using reduce() method

We can also use the reduce() method to count the number of times a specific tag appears in the HTML document. This method applies a function against an accumulator and each element in the array to reduce it to a single value.

const elements = Array.from(document.getElementsByTagName('*'));
const numberOfElements = elements.reduce((accumulator, element) => {
  if (element.tagName.toLowerCase() === 'div') {
    return accumulator + 1;
  }
  return accumulator;
}, 0);

console.log(`Number of <div> tags: ${numberOfElements}`);

In the above code, we are using the reduce() method to count the number of <div> tags in the document. We are first converting the NodeList object returned by getElementsByTagName('*') to an array using Array.from() method. Then, we are applying the reduce() method on the array and checking if the tag name is equal to 'div'. If it is, we are incrementing the accumulator value by 1.

Conclusion

In this article, we discussed three different methods to count HTML element tags using JavaScript. We can use any of these methods depending on our requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe