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.
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.
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With