How can I check if an html tag with its unique id exists twice or more times ?
my pseudocode:
if($('#myId') > 1) {
// exists twice
}
ID selector only catches the first element which is first in the page. So the length of ID selector should be 0
or 1
always.
So use attribute equals selector instead and check it's length.
if($('[id="myId"]').length > 1) {
// exists twice
}
if ($('[id="myId"]').length > 1) {
console.log('twice');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myId"></div>
<div id="myId"></div>
if($("[id=someId]").length > 1) {
//Do Something
}
or
if($("[id=someId]").size() > 1) {
//Do Something
}
if(document.querySelectorAll("[id=someId]").length > 1) {
//Do Something
}
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