X



Home>Tutorial>

What is JavaScript .getElementsByTagName and Examples

Nuelson Penuel Sunday, July 23, 2023 Javascript

JavaScript getElementsByTagName

The JavaScript getElementsByTagName() method allows you to select and access HTML elements based on their tag name. It returns a collection of all the elements with the specified tag name in the document. Here is a detailed explanation along with examples of different use cases:

JavaScript getElementsByTagName Syntax

document.getElementsByTagName(tagName)

JavaScript getElementsByTagName Parameters

tagName: A string value representing the name of the HTML tag you want to select. Return value:A collection of elements with the specified tag name. It typically returns an array-like object called a NodeList, which can be accessed using array-like notation or converted to an actual array using Array.from() or the spread syntax.

How to Use JavaScript getElementsByTagName

The following are some examples. Example 1: Selecting Elements by Tag Name HTML:
<div>Element 1</div>
<div>Element 2</div>
<p>Element 3</p>
JavaScript:
const divElements = document.getElementsByTagName('div');
const pElements = document.getElementsByTagName('p');

console.log(divElements); // Returns a NodeList containing all div elements
console.log(pElements); // Returns a NodeList containing the p element
In this example, .getElementsByTagName() is used to select all div and p elements present in the document. Example 2: Accessing Elements by Index HTML:
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
JavaScript:
const headingElements = document.getElementsByTagName('h1');

console.log(headingElements[0].textContent); // Returns the text of the first h1 element
console.log(headingElements[1].textContent); // Returns the text of the second h1 element
In this example, .getElementsByTagName() returns a NodeList of h1 elements. You can access each element using array-like notation with an index and get their textContent. Example 3: Modifying Elements with a Loop HTML:
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
JavaScript:
const listItems = document.getElementsByTagName('li');

for(let i = 0; i < listItems.length; i++) {
   listItems[i].style.color = 'red';
}
In this example, getElementsByTagName() is used to select the li elements inside the ul tag. A for loop iterates over each element and sets the color property to red. This code will change the color of all list items to red.

Conclusion

getElementsByTagName() is case-insensitive. It selects elements based on their HTML tag name. If you want more specialized or specific element selection, consider using methods like .querySelectorAll() or .getElementById().

| | Views(173)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services