Skip to content
Advertisement

Get multiple elements by Id

I have a page with anchor tags throughout the body like this:

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

The ID is always the same but the name changes.

I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I’ve got to so far:

document.write(document.getElementById("readme").name);

This writes out the name of the first anchor tag. I’m in need of a way to get multiple elements by Id.


Any help is greatly appreciated.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement