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.
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).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With