最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavascriptJquery check if id already exists - Stack Overflow

programmeradmin0浏览0评论

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

my pseudocode:

if($('#myId') > 1) {
  // exists twice
}

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

my pseudocode:

if($('#myId') > 1) {
  // exists twice
}
Share Improve this question asked Jul 29, 2016 at 11:47 utdevutdev 4,11210 gold badges41 silver badges75 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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./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
}
if($("[id='myId']").length > 1) {
    // write your code here
}

This is too simple you might get from small search

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

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

发布评论

评论列表(0)

  1. 暂无评论