Get HTML element by Name
In javascript, getElementsByName() method is useful to access the HTML elements using the name. Here, the name suggests the name attribute of the HTML element. This method returns the collection of HTML elements that includes the particular name. Users can get the length of the collection using the build-in length method.
Syntax:
document.getElementsByName(element_name);
Parameter:
It takes the name of the element which the user wants to access.
Return value:
It returns the collection of elements that have a particular name.
Example: This example demonstrates the use of the getElementsByName method. It prints every element with a particular name 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 w3wiki name --> < h1 name = "w3wiki" >w3wiki sample 1</ h1 > < h1 name = "w3wiki" >w3wiki sample 2</ h1 > < h1 name = "w3wiki" >w3wiki sample 3</ h1 > < p >DOM getElementsByName() Method</ p > < script > // Accessing the element by getElementsByName method let temp = document.getElementsByName("w3wiki"); 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