Is there a way in java script to get only a particular name instead of using document.getElementsByName("x");
which return an array? I have a kind of special situation where i can’t use the id. Any suggestions please?
Thank You.
Asked
Active
Viewed 2.2k times
7
3 Answers
17
Just get the first element:
document.getElementsByName("x")[0];
Or for safety:
function getFirstElementByName(element_name) {
var elements = document.getElementsByName(element_name);
if (elements.length) {
return elements[0];
} else {
return undefined;
}
}
(BTW getElementsByName returns a collection, not an array.)

Quentin
- 914,110
- 126
- 1,211
- 1,335
-
in java script is there a real difference between array and a collection? – Harshana Oct 05 '10 at 04:43
-
Yes. They have different properties. – Quentin Oct 05 '10 at 06:09
9
If you're looking for a single element, take the first one from the nodelist, for example:
var element = document.getElementsByName("x")[0];

Nick Craver
- 623,446
- 136
- 1,297
- 1,155
0
Or use jQuery, so you don't have to bother with all the browser annoyance.
You just have to do this:
$("*[name='x']").first();
To get the first element with that name. If you know the element type than you can use it instead of "*". jQuery will make your life easier every time!

rikas
- 482
- 4
- 25
-
or $("*[name='x']").first() which won't throw an error, if no element is returned. – softcr Oct 04 '10 at 16:25
-
5Lovely, somehow I think in this case `getElementsByName` is far less "annoying". – MooGoo Oct 04 '10 at 16:49