How can I check if an html tag with its unique id exists twice or more times ?
如何检查具有惟一id的html标记是否存在两次或多次?
my pseudocode:
我的伪代码:
if($('#myId') > 1) {
// exists twice
}
4 个解决方案
#1
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.
ID选择器只捕获页面中第一个元素。所以ID选择器的长度应该是0或1。
So use attribute equals selector instead and check it's length.
使用属性= selector来检查它的长度。
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>
#2
2
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
}
#3
0
if($("[id='myId']").length > 1) {
// write your code here
}
#4
0
This is too simple you might get from small search
这太简单了,你可以从小搜索中得到
if($("#" + name).length > 1) {
// if exists twice
}
how many time it exists = $("#" + name).length
它存在的时间= $("#" + name).length
#1
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.
ID选择器只捕获页面中第一个元素。所以ID选择器的长度应该是0或1。
So use attribute equals selector instead and check it's length.
使用属性= selector来检查它的长度。
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>
#2
2
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
}
#3
0
if($("[id='myId']").length > 1) {
// write your code here
}
#4
0
This is too simple you might get from small search
这太简单了,你可以从小搜索中得到
if($("#" + name).length > 1) {
// if exists twice
}
how many time it exists = $("#" + name).length
它存在的时间= $("#" + name).length