6

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.

Joe
  • 14,565
  • 8
  • 47
  • 56
Harshana
  • 6,769
  • 21
  • 92
  • 162

3 Answers3

16

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
  • 857,932
  • 118
  • 1,152
  • 1,264
9

If you're looking for a single element, take the first one from the nodelist, for example:

var element = document.getElementsByName("x")[0];

You can test it out here.

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
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
  • 546
  • 3
  • 22