How can I get a collection of elements by specifying their id
attribute? I want to get the name of all the tags which have the 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 have the same id
in the html.
I want to use ONLY getElementById()
to get an array of elements. How can I do this?
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:
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:
It is illegal to have multiple elements with the same
id
. Theid
is used as an individual identifier. For groups of elements, useclass
, andgetElementsByClassName
instead.document.querySelectorAll("#yourId");
returns all elements whose id isyourId
The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.
The HTML spec required the
ID
attribute to be unique in a page: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
, orgetElementsByClassName
that may be more suited to your requirements, thoughgetElementsByClassName
is new to HTML 5, which is still in draft.we can use document.forms[0].Controlid