Tony
Tony

Reputation: 69

How to check how many different tags exist in a page using JS?

Is there any way to know how many different tags exist in a page? e.g. html; body; div; td; div; can be counted as 4 different tags.

Upvotes: 2

Views: 172

Answers (2)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93193

And the answer is YES :

const allTagNames = Array.from(   //cast the result to array to be able to use array's utilities  like "map"
      document.querySelectorAll('*') // select all elements in the page
   ).map(node => node.tagName) // get only the tagName

const allTagNamesWithoutDuplication = [...new Set(allTagNames)]  // Remove duplicated tagname

And the result will be :

allTagNamesWithoutDuplication.length

const distinctTags=() => {
      const allTagNames = Array.from(   
          document.querySelectorAll('*') 
       ).map(node => node.tagName.toLowerCase()) 
      
      return [...new Set(allTagNames)]
}


const result = distinctTags();

console.log(
    `this page contains ${result.length}  tags : `, result
   
)

Upvotes: 1

SidTheBeard
SidTheBeard

Reputation: 379

The document has a property called all which lists all the tags found on the page. Each of these has a tagName property which is the tag without angle brackets. It comes in uppercase format, but for simplicity just force all tagNames to be lowercase using the .toLowerCase() String method. You can loop through it like I've shown below, storing any tag not yet found on the page, in the tagsFound array.

var tagsFound= [];
for( var index = 0; index < document.all.length; index++ ) {
    if( tagsFound.indexOf(document.all[index].tagName.toLowerCase() == -1 ) {
        // Tag was not found before this
        tags.push(document.all[index].tagName.toLowerCase());
    }
}

Then, the number of unique tags found would be

tagsFound.length

Upvotes: 1

Related Questions