Reputation: 67
I understand that unlike class, an ID should be unique in a HTML document. What will happen if I use the same id multiple times for multiple HTML elements? Will it throw any error? or will it just not work?
I tried to try this scenario but wanted to know more context around it.
Upvotes: 1
Views: 2650
Reputation: 68
Nothing really happens. JavaScript and CSS selectors will only select the first element they find with the id. It's not like your website will crash. It's just very bad practice because an id should be unique on each page.
Upvotes: 0
Reputation: 1
I have tried it and it works if we put same id name for multiple elements its going to change properties where the id is same
Upvotes: 0
Reputation: 384
Yes, Unlike html class, We cannot apply same id in multiple html elements, It will not throw any error but only the first element with the id will work and other elements won't work.
$('#foo').on('click',function(){
alert('work')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">Click me</div>
$('#foo').on('click',function(){
alert(' work')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">Click me(work)</div>
<div id="foo">Click me(won't work)</div>
<div id="foo">Click me(won't work)</div>
Upvotes: 3
Reputation: 371233
It would be invalid HTML.
In some environments, it may produce a console warning that multiple IDs in a single document is invalid. Harmless, but annoying.
It will prevent document.getElementById
from working properly for those elements, because getElementById
selects by ID, but there should only be one element with a given ID in the document. Similarly, it may prevent querySelector
and querySelectorAll
with ID selectors from working properly.
Using the same ID multiple times may well not break your application in most cases, but just because it might be doable in some circumstances doesn't mean it's a good idea. There's no reason to do it, so don't.
Upvotes: 2