Get HTML elements by TagName
In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.
Syntax:
document.getElementsByTagName(Tag_name);
Parameter:
It takes a single parameter which is the tag name.
Return value:
It returns the collection of elements that includes the tag which passed as a parameter.
Example: This example demonstrates the use of the getElementsByTagName method. It prints every element with a particular tag into the console. Users can open the console in the Chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title >Document</ title > </ head > < body > <!-- Multiple html element with h1 tag --> < h1 >w3wiki sample 1</ h1 > < h1 >w3wiki sample 2</ h1 > < h1 >w3wiki sample 3</ h1 > < p >DOM getElementsByTagName() Method</ p > < script > // Accessing the element by // getElementsByTagName method let temp = document.getElementsByTagName("h1"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </ script > </ body > </ html > |
Output:
Different ways to access HTML elements using JavaScript
Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structure of the web page.
From the DOM, users can access HTML elements in five different ways in JavaScript:
Table of Content
- Get HTML element by Id
- Get HTML element by className
- Get HTML element by Name
- Get HTML elements by TagName
- Get HTML elements by CSS Selector