How to get element by name in HTML – getElementsByName

The getElementsByName() method is use to get the element by name. However be aware of the getElementsByName() method always return an array as output.










Caution
The method always return an array, and we have to use [] to access the value.

For example

alert(document.getElementsByName("myInput").value);

It will prompt out an undefined value

alert(document.getElementsByName("myInput")[0].value);

It will prompt out an expected ‘testing’ value

One more time, there are no getElementByName() exists, it is getElementsByName(), with a ‘s’ 🙂

17 comments on “How to get element by name in HTML – getElementsByName

  1. how I can use this method with JSF if I want to take the value of Please?

    Reply
  2. Explanation: This is because there can be multime inputs with the same name, such as checkboxes, radios and select options.

    Reply
  3. hi sir,
    its working fine, but if i want to get the collection of all the names, then i was not able to get it.. plz help me out from this..

    thanks in advance,
    chaitanya

    Reply
  4. sir,
    sometimes, its throwing me error that value of ‘c’ is undefined, when i use,

    var c=0;

    getElementsByName(‘name’)[c++].value;

    this kind of error was thrown when i was trying to access my application on firefox…

    [18:40:07.772] TypeError: document.getElementsByName(…)[(intermediate value)] is undefined

    plz, sir, help me out…

    thanks in advance.. 🙂

    Reply
  5. How you get all values? wiouth using for, I know with “getElementsByName” will give you all inputs, but I need each .value on every input, wiouth using a for later.
    because the array is = []
    you can use a for “array[i].value” to create another array is = [“some value”], but I dont want to use for =(

    Reply
  6. thank you Mkyong. ‘s’ letter and returning array gave me hard time

    Reply
  7. thank u so much mkyong, this helped me a lot, intitially, i was using the property without “s”, n clearly emphasised on that,thanks a lot… 😉

    Reply
  8. But there is getElementById, which returns 1 element, because ID is supposed to be unique to each element. If not, the first occurence is returned.

    getElementById

    (without s, case-sensitive = not ID or id)

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *