Javascript / jquery checks if identifier exists

How to check if an html tag with its unique identifier exists two or more times?

my pseudo code:

if($('#myId') > 1) {
  // exists twice
}
+4
source share
4 answers

The identifier selector only picks up the first element, which is the first on the page. Therefore, the length of the selector identifier must be 0or 1always.

So use the attribute instead of the selector and check its 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>
Run codeHide result
+5
source

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
}
+2
source

,

if($("#" + name).length > 1) {
  // if exists twice 
}

exists = $("#" + name).length

0
if($("[id='myId']").length > 1) {
    // write your code here
}
0

Source: https://habr.com/ru/post/1649528/


All Articles