Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / Jquery check if id already exists

How can I check if an html tag with its unique id exists twice or more times ?

my pseudocode:

if($('#myId') > 1) {
  // exists twice
}
like image 985
utdev Avatar asked Mar 12 '23 14:03

utdev


2 Answers

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>
like image 175
Pranav C Balan Avatar answered Mar 17 '23 07:03

Pranav C Balan


JQuery

if($("[id=someId]").length > 1) {
    //Do Something
}

or

if($("[id=someId]").size() > 1) {
    //Do Something
}

Javascript

if(document.querySelectorAll("[id=someId]").length > 1) {
    //Do Something
}
like image 41
Error404 Avatar answered Mar 17 '23 06:03

Error404