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’ 🙂
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 =(
getElementsByName doesn’t return an array, it returns a NodeList. While they look similar, they’re definitely not the same: https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array
GyIhidH7FpeJpwQt nx1S
how I can use this method with JSF if I want to take the value of Please?
Explanation: This is because there can be multime inputs with the same name, such as checkboxes, radios and select options.
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
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.. 🙂
thank you Mkyong. ‘s’ letter and returning array gave me hard time
Thank you so much it was useful to me alot…….
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… 😉
thanks this is help me
thanks
Thanks a lot!!
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)
thanks a lot for this code ,it solved my problem
Thanks, this helped alot
wc, good to know this is helpful.