tags:

views:

124

answers:

5

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?

+2  A: 

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.

remi bourgarel
If the elements support a name attribute, which most don't. There has been a heavy push to get rid of it except for form controls.
David Dorward
Indeed but it's the only solution (afaik) if he doesn't use a js framework, and it'll work for every elements even if (according to w3c) the element doesn't support this attribute.
remi bourgarel
You don't need a JS framework to use gEBCN, you can test for the existence of the function and then fallback to a function that loops over elements and checks their classes - plenty of implementations out on the net.
David Dorward
+3  A: 

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.

Delan Azabani
getElementsByClassName is not support in IE currently.
Floyd
A value for `class` should also not be used for identification, when name is a perfectly valid approach.
Noon Silk
Most elements do not support a name attribute, so that isn't a very practical suggestion. A class is a group of things that have something in common. If someone wants to grab a bundle of things with JS, then they must have something in common. Therefore class is an **excellent** choice for this. It is **not** an attribute that is designed solely to hang CSS from. The only problem is the limited browser support for getElementsByClassName, but there are cross-browser implementations of that (including standalone ones and in YUI and jQuery)
David Dorward
(NB: The answer could be improved by adding a couple of links to such implementations)
David Dorward
@Noon Silk: The class element was designed for identification purposes. So it *should not* be not used for identification. The HTML4 spec says: `The class attribute has several roles in HTML: 1-As a style sheet selector. 2-For general purpose processing by user agents.`. Using `class` for identification is a perfectly valid approach - that's what it was intended for!
slebetman
@David I think we'll agree to disagree. @Slebetman: I think you've made a typo on your response, it contradicts itself.
Noon Silk
@Noon Silk — *why* do you think classes are inappropriate for this?
David Dorward
@David: Arguing with someone, anyone, about web standards is about the least productive way to spend my time.
Noon Silk
@Noon Silk - David wasn't asking for an argument, merely an explanation. Refusing to discuss something with somebody is not a good way to convince them to agree with your opinion. (Well, that's my opinion, anyway)
belugabob
@belugabob: What you don't see is that I don't care if he agrees or not.
Noon Silk
That's just the point, it's not agreement that David is after - merely understanding of why you would never use the class attribute for purely identification purposes. You may not be interested in the opinions of others but, maybe, others are interested in yours.
belugabob
@Noon Silk, please explain why you don't believe that `class` is good for grouping? Semantically, it's *better* than `name`.
Delan Azabani
belugabob: not so much. It's not a matter of opinion as to whether `name` is a valid attribute for most elements: it simply isn't, so Noon Silk would seem to be in denial.
Tim Down
I believe that `name` only works for `form` elements. Also, the real purpose of `name` is to name the query attribute names when they are sent to the server. The only time when they should be used on multiple elements, is to group radio buttons.
Delan Azabani
@Delan — there are quite a few elements that support name, but it was being slowly phased out (fewer support them in XHTML 1.1 than in HTML 4.01 for instance). There are plenty of times when it is useful to have multiple form elements with the same name other than radio buttons though ('tick all that apply' checkboxes spring to mind).
David Dorward
This will be my last reply here. Any of you are free to email me direclty where I will be happy to discuss anything in a polite and friendly manner; I will not discuss any item over this website, as it is counterproductive to legimate discussion and useful results.
Noon Silk
Isn't that the whole point of StackOverflow - to pool a whole raft of opinions and ideas, for others to learn from?
belugabob
+5  A: 

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.

Oded
Can the downvote please explain why?
Oded
I was also downvoted; I've deleted my answer as it is effectively a duplicate of yours. I suspect the downvoter has no legitimate basis for his concerns other than a self-important opinion.
Noon Silk
Downvote from me too, `class` is semantically better than `name`, which is not correctly used here. I believe that `name` only works for `form` elements. Also, the real purpose of `name` is to name the query attribute names when they are sent to the server. The only time when they should be used on multiple elements, is to group radio buttons.
Delan Azabani
@Delan Azabani - in the context of the question, it is unclear if either `getElementsByName` or `getElementsByClassName` are suitable solutions. I have added some detail on both.
Oded
Ah, okay then. I've withdrawn my downvote.
Delan Azabani
A: 

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.

Moin Zaman
Well, you can have more than one element with the same ID, but you shouldn't - and the consequences of doing so is unpredictable, due to differences betwen browsers. This is the root of a lot of problems - if all browsers rejected pages with duplicate ID attributes, this whole discussion would be more or less unnecessary. (In an ideal world...)
belugabob
A: 

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)];
}
Paul Butcher
Indeed a silly workaround. But why are you defining a wrapper function around `document.getElementById` in your added part? That's completely useless (other than using a shorter alias like `$` to achieve the same).
Marcel Korpel
The specific requirement of the OP is to get an array of elements. `document.getElementById` returns just one element (not in an array), my function `getElementsById` returns an array containing all of the elements with a given id in a valid document.
Paul Butcher