To select elements by tag name e.g., div, p, span, a, ul, you use the Element.getElementsByTagName()
method:
let elements = element.getElementsByTagName(tagName)
Code language: JavaScript (javascript)
The getElementsByTagName()
method returns a live HTMLCollection
of elements with the given tag name.
The following show an HTML document with some elements:
<html>
<head>
<title>JavaScript getElementsByTagName() example</title>
</head>
<body>
<div id="container">
<a href="https://nodejs.org/">Node.js</a>
<a href="https://openjsf.org/">OpenJS Foundation</a>
</div>
<a href="https://github.com/tc39">Ecma TC39</a>
<script src="js/app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
And the following code shows the number of links and their href
attributes:
let links = document.getElementsByTagName('a');
// return the number of links
console.log('Link Count:', links.length);
// show the href of links
for (let i = 0; i < links.length; i++) {
console.log(links[i].href);
}
Code language: JavaScript (javascript)
Output:
Link Count: 3
https://nodejs.org/
https://openjsf.org/
https://github.com/tc39
Code language: JavaScript (javascript)
To get the link elements inside an element, you select the container element first and call the getElementsByTagName()
method on the selected element:
const container = document.getElementById('container');
const links = container.getElementsByTagName('a');
for (let i = 0; i < links.length; i++) {
console.log(links[i].href);
}
Code language: JavaScript (javascript)
Output:
https://nodejs.org/
https://openjsf.org/
Code language: JavaScript (javascript)
Was this tutorial helpful ?