The getElementByName() method in JavaScript is used to retrieve a reference to the first element with a specified value for the name attribute within the current document or within a specified element. It is similar to getElementById(), but instead of searching for elements by their id, it searches for elements by their name attribute.
Syntax:
document.getElementsByName(name)
Parameters:
name(required):- A string representing the value of the
nameattribute of the elements to be retrieved.
- A string representing the value of the
Return Value:
- An
HTMLCollectionobject representing a live collection of elements with the specified name attribute value. If no elements are found, an empty collection is returned.
getElementByName Example
Note:
- The
nameattribute should be unique within the document or within a specific scope to ensure accurate retrieval of elements. - If multiple elements have the same name,
getElementsByName()returns a collection of all matching elements. - Since
getElementsByName()returns a liveHTMLCollection, changes to the DOM are reflected dynamically in the collection.
Compatibility:
getElementsByName()is supported in all major browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer.