How can I get a collection of elements by specifying their id
attribute? I want to get the name of all the tags which have the same id
in the html.
I want to use ONLY getElementById()
to get an array of elements. How can I do this?
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.
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.
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.
The HTML spec requires the id
attribute to be unique in a page:
[T]he id attribute value must be unique amongst all the IDs in the element's tree
If you have several elements with the same ID, your HTML is not valid.
So, document.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 a list of elements: getElementsByName
or getElementsByClassName
that may be more suited to your requirements.
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