JavaScript: How to get element by its name
You can use JavaScript to retrieve an HTML element by using its name with the getElementsByName() method.
This method always return an array of elements with the name attribute that you specified as its argument.
For example, suppose you have the following HTML <body> tag:
<body>
<p name="paragraph">Hello world</p>
<p name="paragraph">Bonjour le monde</p>
<p name="paragraph">Olá Mundo</p>
</body>
You can fetch all three <p> elements using its name as follows:
const paragraphs = document.getElementsByName("paragraph");
console.log(paragraphs); // NodeList [p, p, p]
console.log(paragraphs[0].innerHTML); // Hello world
console.log(paragraphs[1].innerHTML); // Bonjour le monde
console.log(paragraphs[2].innerHTML); // Olá Mundo
When there is no element with the specified name attribute, the method will simply return an empty array [].
More JavaScript tutorials
See allJavaScript
Sort Keys in Map Using JavaScript
Dec 11, 2023
JavaScript
Get Element by Data Attribute Using JavaScript
Dec 8, 2023
JavaScript
Convert Milliseconds to Hours Minutes Seconds in JavaScript
Dec 6, 2023
JavaScript
JavaScript Get the Index of Max Value in Array
Nov 16, 2023
JavaScript
JavaScript Check if Value is an Object
Nov 15, 2023