简体   繁体   中英

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
}

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> 

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
}

This is too simple you might get from small search

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

how many time it exists = $("#" + name).length

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM