Get multiple elements by Id

If you can change the markup, you might want to use class instead.

HTML

<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

JS

var elements = document.getElementsByClassName("test");
var names = '';
for(var i = 0; i < elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo


Today you can select elements with the same id attribute this way:

document.querySelectorAll('[id=test]');

Or this way with jQuery:

$('[id=test]');

CSS selector #test { ... } should work also for all elements with id = "test". Вut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id. Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .

For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).


As oppose to what others might say, using the same Id for multiple elements will not stop the page from being loaded, but when trying to select an element by Id, the only element returned is the first element with the id specified. Not to mention using the same id is not even valid HTML.

That being so, never use duplicate id attributes. If you are thinking you need to, then you are looking for class instead. For example:

<div id="div1" class="mydiv">Content here</div>
<div id="div2" class="mydiv">Content here</div>
<div id="div3" class="mydiv">Content here</div>

Notice how each given element has a different id, but the same class. As oppose to what you did above, this is legal HTML syntax. Any CSS styles you use for '.mydiv' (the dot means class) will correctly work for each individual element with the same class.

With a little help from Snipplr, you may use this to get every element by specifiying a certain class name:

function getAllByClass(classname, node) {

    if (!document.getElementsByClassName) {
        if (!node) {
            node =  document.body;
        }

        var a = [],
            re = new RegExp('\\b' + classname + '\\b'),
            els = node.getElementsByTagName("*");

        for (var i = 0, j = els.length; i < j; i++) {
            if (re.test(els[i].className)) {
                a.push(els[i]);
            }
        }
    } else {
        return document.getElementsByClassName(classname);
    }

    return a;
}

The above script will return an Array, so make sure you adjust properly for that.