JavaScript getElementsByTagName
The getElementsByTagName()
method is a built-in JavaScript method that returns a collection of all the elements in a document with the specified tag name.
Syntax
document.getElementsByTagName(tagName);
where tagName
is a string representing the name of the tag. It can be a standard HTML tag name (e.g. "div"
, "p"
, "a"
) or a custom tag name.
Example
<!DOCTYPE html>
<html>
<head>
<title>Example using getElementsByTagName()</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>Here's some text</p>
<div>
<p>A paragraph inside a div</p>
<span>A span inside a div</span>
</div>
<p>More text</p>
<script>
const allP = document.getElementsByTagName("p");
console.log(allP);
</script>
</body>
</html>
Output
The output of the example above when we run it in the console will be a collection of all the p
tags in the document:
NodeList(3) [p, p, p]
Explanation
The getElementsByTagName()
method returns a collection of all the elements in the document with the specified tag name. In the example above, we are using it to get all the p
tags in the document. The output is a NodeList
object, which is an array-like collection of nodes.
Use
The getElementsByTagName()
method can be used to target specific elements on a web page and manipulate them using JavaScript. For example, we could use it to change the text of all the p
tags on a page, or to add a CSS class to all the div
tags on a page.
Important Points
- The
getElementsByTagName()
method returns aNodeList
object that is an array-like collection of nodes. - The
tagName
argument is case-insensitive. - If there are no elements in the document with the specified tag name, the
getElementsByTagName()
method returns an emptyNodeList
object.
Summary
The getElementsByTagName()
method is a useful tool in JavaScript that lets us collect a collection of all the elements in a document with the specified tag name. It returns a NodeList
object that we can manipulate using other JavaScript methods.