【发布时间】:2016-12-04 03:01:59
【问题描述】:
如何检查具有唯一 id 的 html 标签是否存在两次或更多次?
我的伪代码:
if($('#myId') > 1) {
// exists twice
}
【问题讨论】:
标签: javascript jquery html exists
如何检查具有唯一 id 的 html 标签是否存在两次或更多次?
我的伪代码:
if($('#myId') > 1) {
// exists twice
}
【问题讨论】:
标签: javascript jquery html exists
这太简单了,你可能会从小搜索中得到
if($("#" + name).length > 1) {
// if exists twice
}
多少次了exists = $("#" + name).length
【讨论】:
if($("[id=someId]").length > 1) {
//Do Something
}
或
if($("[id=someId]").size() > 1) {
//Do Something
}
if(document.querySelectorAll("[id=someId]").length > 1) {
//Do Something
}
【讨论】:
ID selector 只捕获页面中的第一个元素。所以ID selector的长度应该是0或者1。
所以请改用attribute equals 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>
【讨论】:
if($("[id='myId']").length > 1) {
// write your code here
}
【讨论】: