Returns a nodelist collection with a given name in the (X)HTML document.
elements = document.getElementsByName(name)
elements is a live NodeList Collectionname is the value of the name attribute of the element.<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<form name="up"><input type="text"></form>
<div name="down"><input type="text"></div>
<script>
var up_forms = document.getElementsByName("up");
console.log(up_forms[0].tagName); // returns "FORM"
</script>
</body>
</html>
The name attribute is only applicable to (X)HTML documents. The method returns a live NodeList Collection that contains all elements with a given value for the name attribute, such as <meta> or <object> or even if name is placed on elements which do not support a name attribute at all.
The getElementsByName method works differently in different browsers. In IE < 10, getElementsByName() method will also return elements that have an id attribute with the specified value. so you should be careful not to use the same string as both a name and an ID.
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'Document.getElementsByName()' in that specification. | Living Standard | |
| Document Object Model (DOM) Level 2 HTML Specification The definition of 'Document.getElementsByName()' in that specification. | Obsolete | Initial definition |
document.getElementById() to return a reference to an element by its id
document.getElementsByTagName() to return references on elements with the given tag namedocument.querySelector() for powerful selectors via queries like 'div.myclass'
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/document/getElementsByName