How to Returns a NodeList containing all elements with a specified name in JavaScript ?


In JavaScript, we can use the getElementsByTagName() method to return a NodeList containing all elements with a specified name.

The syntax for using getElementsByTagName() method is as follows:

document.getElementsByTagName(name);

Here, name is the name of the element we want to select. For example, if we want to select all the <p> elements in the document, we can use the following code:

var paragraphs = document.getElementsByTagName("p");

This will return a NodeList containing all the <p> elements in the document.

We can also use this method to select elements within a specific element. For example, if we want to select all the <p> elements within a <div> element with an id of "myDiv", we can use the following code:

var myDiv = document.getElementById("myDiv");
var paragraphs = myDiv.getElementsByTagName("p");

This will return a NodeList containing all the <p> elements within the <div> element with an id of "myDiv".

Another way to select elements with a specific name is by using the querySelectorAll() method. This method allows us to select elements using CSS selectors. For example, if we want to select all the <p> elements in the document, we can use the following code:

var paragraphs = document.querySelectorAll("p");

This will return a NodeList containing all the <p> elements in the document.

We can also use this method to select elements within a specific element. For example, if we want to select all the <p> elements within a <div> element with an id of "myDiv", we can use the following code:

var myDiv = document.getElementById("myDiv");
var paragraphs = myDiv.querySelectorAll("p");

This will return a NodeList containing all the <p> elements within the <div> element with an id of "myDiv".



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.