How to Loop Through All HTML Tags Using JavaScript?

Estimated read time 1 min read

You can use the document.getElementsByTagName method to loop through all HTML tags of a certain type. This method returns a collection of elements that match the tag name you specify as an argument. You can use a for loop to iterate over the collection and perform actions on each element.

Example:

const elements = document.getElementsByTagName("p");
for (let i = 0; i < elements.length; i++) {
    console.log(elements[i].innerHTML);
}

In the example above, the getElementsByTagName method returns a collection of all p tags on the page. The for loop then iterates over the collection and logs the content (innerHTML) of each p tag to the console.

You can replace "p" with any other HTML tag name to loop through elements of that type.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply