DEV Community

Cover image for Using getElementsByName Method in Javascript
Jamie Mc Manus
Jamie Mc Manus

Posted on

Using getElementsByName Method in Javascript

Image by Tudor Baciu on Unsplash

HTML Name attribute

This is an attribute for a HTML element that is used to identify the element by assigning it a name.

One of the most common uses of the name attribute would be to use it to identify the form inputs submitted to the server ( this is opposed to using the Id attribute which would be the most common way to identify an element on the Clientside - which cannot be used because the Id attribute does not get passed to the server on form Submit ).

Example of name attribute :


<input name="firstname" Placeholder="Enter Your First Name"/>

<input name="lastname" Placeholder="Enter Your Last Name"/>

Enter fullscreen mode Exit fullscreen mode

Accessing via Javascript

To access a HTML element/s by the name attribute we use getElementsByName which returns a NodeList of all elements that have the given name attribute

eg:


getElementsByTagName('attributename')

Enter fullscreen mode Exit fullscreen mode

The NodeList is an array like object - this means that it is missing some array features like push , pop etc .

Example:


<div id="surveyitems">



  <button name="survey" >JS Rocks</button>

  <button name="survey" >JS Doesn't Rock</button>

  <button name="survey" >I don't know what JS is</button>



</div>



Enter fullscreen mode Exit fullscreen mode

let survey = document.getElementsByName('survey')

for (let item of survey) {

    console.log(item.innerText);

}



for (var i = 0; i < survey.length; i++) {

    console.log(list[i].innerText);

}



survey.forEach(element => {

    console.log(element.innerText)

});

Enter fullscreen mode Exit fullscreen mode

Also remember that getElementsByName also returns a Live nodelist as opposed to a static one like one returned by querySelectorAll , so even valid elements created after the point that you assign it to a variable will appear in your list.

See the below example -

Notice how the count incremented yet we never updated the surveylist variable ? This is because the NodeList is Live , so make sure you don't get caught out by this !

Slán go fóill

Feel free to ask questions, comment or contribute below!

And if you're feeling generous you can buy me a coffee with the link below ( and yes its all for coffee, I drink a copious amount of it while writing ☕ )

Buy Me A Coffee

Top comments (0)