Jamie McManus
Jamie McManus

Jamie McManus

Using getElementsByName Method in Javascript

Using getElementsByName Method in Javascript

Jamie McManus's photo
Jamie McManus
·Feb 22, 2022·

2 min read

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"/>

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')

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>

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)

});

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 -

{% jsfiddle jsfiddle.net/6wc8yh0L %}

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

Did you find this article valuable?

Support Jamie McManus by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this