Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
osnoz Avatar asked Mar 17 '11 12:03

osnoz


People also ask

Can you get multiple elements by ID?

As per the W3c spec, id attributes "must be unique within a document". That's the whole point of a unique identifier, and is why you don't have DOM methods to get multiple elements with the same ID (since the latter doesn't make any sense).

How do I select all elements by ID?

Use the document. querySelectorAll() method to get all elements whose id starts with a specific string, e.g. document. querySelectorAll('[id^="box"]') . The method returns a NodeList containing all the elements that match the provided selector.

How do I querySelector multiple ids?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.

How do I use multiple documents in getElementById?

You could use document. querySelectorAll() that allows you to specify multiple ids in a CSS selector string . You could put a common class names on all those nodes and use document. getElementsByClassName() with a single class name.


1 Answers

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

like image 61
erickb Avatar answered Sep 20 '22 01:09

erickb