JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to select HTML elements by Tag Name in JavaScript?

HTML elements are also called tags and to select them by their tag name, you have to call document.getElementByTagName() method.

let htmlElements = document.getElementsByTagName("tag-name");

document.getElementsByTagName() method accepts the name of the HTML elements that you want to select. If the tag name matches the names present in the DOM tree, it returns an array of HTMLCollection; otherwise, it returns null.

Examples of tag names are p, div, a, span, img, and others.

Note: In an HTML document, there can be more than one HTML element with the same tag name, so you must use for loop to iterate through all the HTML elements returned by the document.getElementsByTagName() method.

HTML code

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript document.getElementsByTagName() Example</title>
</head>
<body>
  <div id="image-container">
    <img src="/images/numpylogo.png" alt="NumPy logo" />
    <img src="/images/javascript.png" alt="JavaScript logo" />
    <img src="/images/gitlogo.png" alt="Git logo" />
    <img src="/images/matplotliblogo.png" alt="Matplotlib logo" />
  </div>
</body>
</html>

JavaScript code

let images = document.getElementsByTagName('img');

console.log(`There are ${images.length} images.`)

console.log('Images URL')
for(let image of images){
  console.log(image.src);
}

Output

There are 4 images.
Images URL
https://www.tutorialsandyou.com/images/numpylogo.png
https://www.tutorialsandyou.com/images/javascript.png
https://www.tutorialsandyou.com/images/gitlogo.png
https://www.tutorialsandyou.com/images/matplotliblogo.png

You can also use getElementsByTagName() method on the parent element to access the elements inside an element. Let's rewrite the above code by selecting the image container first and then all the img elements inside it.

let imageContainer = document.getElementById('image-container');

let images = imageContainer.getElementsByTagName('img')

console.log(`There are ${images.length} images.`)

console.log('Images URL')
for(let image of images){
  console.log(image.src);
}

This code is just another way of writing the program and will give the same output.

Recommended Posts