Can multiple HTML elements have the same ID if they\'re of different element types? Is a scenario like this valid? Eg:
div#foo
span#foo
a#foo
How about a pragmatic answer.
Let's go to youtube and run this code
Object.fromEntries(Object.entries([...document.querySelectorAll('[id]')].reduce((s, e) => { s[e.id] = (s[e.id] || 0) + 1; return s; }, {})).filter(([k,v]) => v > 1))
and see all the repeated ids.
Changing the code above to show ids repeated more than 10 times here's the list it produced
additional-metadata-line: 43
avatar: 46
avatar-link: 43
button: 120
buttons: 45
byline-container: 45
channel-name: 44
container: 51
content: 49
details: 43
dismissable: 46
dismissed: 46
dismissed-content: 43
hover-overlays: 45
img: 90
menu: 50
meta: 44
metadata: 44
metadata-line: 43
mouseover-overlay: 45
overlays: 45
repeat: 36
separator: 43
text: 49
text-container: 44
thumbnail: 46
tooltip: 80
top-level-buttons: 45
video-title: 43
video-title-link: 43
Other sites that use the same id more than once include Amazon.com, ebay.com, expedia.com, cnn.com
clearly ids are just another piece of metadata on an element.
getElementById
is pretty much obsolete. You can use querySelectorAll
for all elements or querySelector
for the first, regardless of selector so if you want all elements with id foo
then
document.querySelectorAll('#foo') // returns all elements with id="foo"
where as if you want only the first element use querySelector
document.querySelector('#foo') // returns the first element with id="foo"
document.querySelector('.foo') // returns the first element with class "foo"
document.querySelector('foo') // returns the first element
document.querySelector('foo .foo #foo') // returns the first element with
// id="foo" that has an ancestor
// with class "foo" who has an
// ancestor element.
And we can see that using selectors we can find different elements with the same id.
function addClick(selector, add) {
document.querySelector(selector).addEventListener('click', function() {
const e = this.parentElement.querySelector('span');
e.textContent = parseInt(e.textContent) + add;
});
}
addClick('.e #foo', 1);
addClick('.f #foo', 10);
body { font-size: x-large; font-weight: bold; }
.a #foo { color: red; }
.b #foo { color: green; }
div:nth-child(3) #foo { color: blue; }
#foo { color: purple }
a
b
c
d
: 0
: 0
tags can reference ids as in
. Clicking it will jump the document to the first element with
id="foo"
. Similarly the hash tag in the URL which is effectively the same feature.
tags have a
for
attribute that specifies which element they are labeling by id. Clicking the label clicks/activates/give-the-focus-to the corresponding element. The label will only affect the first element with a matching id
label { user-select: none; }
nested for checking
Otherwise, id
is just another tool in your toolbox.