Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a html element by name

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.

like image 221
Harshana Avatar asked Oct 04 '10 15:10

Harshana


People also ask

How do I find an element by tag name?

The getElementsByTagName() is a method of the document or element object. The getElementsByTagName() accepts a tag name and returns a list of elements with the matching tag name. The getElementsByTagName() returns a live HTMLCollection of elements. The HTMLCollection is an array-like object.

How do I grab an element by ID?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Can we get element by class name?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection. The getElementsByClassName() property is read-only.


2 Answers

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

like image 173
Quentin Avatar answered Sep 21 '22 08:09

Quentin


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.

like image 39
Nick Craver Avatar answered Sep 24 '22 08:09

Nick Craver