Tutorials using JS
Find Elements by Tag Name
to find elements in the document that has a given tag name, use Document.getElementsByTagName()
function
Syntax
The syntax of getElementsByTagName()
function is
document.getElementsByTagName("tag_name")
where
document
object is the root node of the HTML documentgetElementsByTagName
is the function nametag_name
is the node name (a for links, p for paragraphs, etc.,) which is used for searching the document
the function call returns a NodeList object which is like an array of elements, that match the given tag name
Examples
1. find elements whose tag name is p
in the following document, we have two paragraphs. when user clicks on Click Me
button, we find the elements by tag name 'p'
and change their background color to yellow
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Find Elements by Tag Name</h2>
<button id="myBtn">Click Me</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
//get all the elements whose tag is 'p'
const paras = document.getElementsByTagName('p');
for ( let i = 0; i < paras.length; ++i) {
paras[i].style.background = 'yellow';
}
});
</script>
</body>
</html>