How can I get a collection of elements by specifying their id attribute? I want to get the name of all the tags which has same id in the html.
I want to use ONLY getElementById() to get an array of elements. How can I do this?
How can I get a collection of elements by specifying their id attribute? I want to get the name of all the tags which has same id in the html.
I want to use ONLY getElementById() to get an array of elements. How can I do this?
The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.
It is illegal to have multiple elements with the same id. The id is used as an individual identifier. For groups of elements, use class, and getElementsByClassName instead.
The HTML spec required the ID attribute to be unique in a page:
This attribute assigns a name to an element. This name must be unique in a document.
If you have several elements with the same ID, your HTML is not valid.
So, getElementById() should only ever return one element. You can't make it return multiple elements.
There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.
You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.
Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.
Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:
function whywouldyoudothis() {
var n = document.getElementById("non-unique-id");
var a = [];
var i;
while(n) {
a.push(n);
n.id = "a-different-id";
n = document.getElementById("non-unique-id");
}
for(i = 0;i < a.length; ++i) {
a[i].id = "non-unique-id";
}
return a;
}
However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.
EDIT: Given a valid document, the same effect could be achieved thus:
function getElementsById(id) {
return [document.getElementById(id)];
}