JQuery 检查 DOM 中的重复 id

我正在用 ASP.NET MVC 编写应用程序。与传统的 ASP.NET 相比,您要负责在生成的页面中创建所有 id。ASP.NET 会给你一个恶心但是独一无二的 ID。

我想添加一个快速的小 jQuery 脚本来检查我的文档是否有重复的 id。它们可能是 DIVS、图像、复选框、按钮等的 ID。

<div id="pnlMain"> My main panel </div>
<div id="pnlMain"> Oops we accidentally used the same ID </div>

我正在寻找一个集和忘记类型实用程序,只会警告我,当我做一些粗心大意。

是的,我将只在测试期间使用这个,并且其他选择(如防火插件)也是受欢迎的。

54470 次浏览

Why don't you just validate your html?

Double ID's are not allowed, and normally you will get a parse-error.

You should try HTML Validator (Firefox extension). It'll definitely tell you the page has duplicate ids and much more.

This might do the trick It will alert all the ids of elements with duplicates.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="jquery-1.3.1.min.js"></script>
<script type="text/javascript">
function findDupes()
{
var all = $("*");
for(var i = 0; i < all.length; i++)
{
if (all[i].id.length > 0 && $("[id='" + all[i].id + "']").length > 1) alert(all[i].id);
}
}
</script>
</head>
<body onload="findDupes()">
<div id="s"></div>
<div id="f"></div>
<div id="g"></div>
<div id="h"></div>
<div id="d"></div>
<div id="j"></div>
<div id="k"></div>
<div id="l"></div>
<div id="d"></div>
<div id="e"></div>
</body>
</html>

The following will log a warning to the console:

// Warning Duplicate IDs
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
console.warn('Multiple IDs #'+this.id);
});

Yet another way of locating duplicates but this will add a class of error so it will have red text:

// waits for document load then highlights any duplicate element id's
$(function(){ highlight_duplicates();});


function highlight_duplicates() {
// add errors when duplicate element id's exist
$('[id]').each(function(){ // iterate all id's on the page
var elements_with_specified_id = $('[id='+this.id+']');
if(elements_with_specified_id.length>1){
elements_with_specified_id.addClass('error');
}
});




// update flash area when warning or errors are present
var number_of_errors = $('.error').length;
if(number_of_errors > 0)
$('#notice').append('<p class="error">The '+number_of_errors+
' items below in Red have identical ids.  Please remove one of the items from its associated report!</p>');
}

This version is somewhat faster, and you can copy it to a bookmark button to make it a bookmarklet.

javascript:(function () {
var ids = {};
var found = false;
$('[id]').each(function() {
if (this.id && ids[this.id]) {
found = true;
console.warn('Duplicate ID #'+this.id);
}
ids[this.id] = 1;
});
if (!found) console.log('No duplicate IDs found');
})();

I have a big page, so that script runs too slow to finish (multiple "continue script" messages). This works fine.

(function () {
var elms = document.getElementsByTagName("*"), i, len, ids = {}, id;
for (i = 0, len = elms.length; i < len; i += 1) {
id = elms[i].id || null;
if (id) {
ids[id] =  ids.hasOwnProperty(id) ? ids[id] +=1 : 0;
}
}
for (id in ids) {
if (ids.hasOwnProperty(id)) {
if (ids[id]) {
console.warn("Multiple IDs #" + id);
}
}
}
}());

I like this because it spits out the actual elements to the console. It makes it easier to investigate what's going on.

function CheckForDuplicateIds() {
var ids = {};
var duplicates = [];


$("[id]").each(function() {
var thisId = $(this).attr("id");
if (ids[thisId] == null) {
ids[thisId] = true;
} else {
if (ids[thisId] == true) {
duplicates.push(thisId);
ids[thisId] = false;
}
}
});
if (duplicates.length > 0) {
console.log("=======================================================");
console.log("The following " + duplicates.length + " ids are used by multiple DOM elements:");
console.log("=======================================================");
$(duplicates).each(function() {
console.warn("Elements with an id of " + this + ":");
$("[id='" + this + "']").each(function() {
console.log(this);
});
console.log("");
});
} else {
console.log("No duplicate ids were found.");
}
return "Duplicate ID check complete.";

}

I've created a function where you can inspect a specifically element searching for duplicated ids within or the entire page:

function duplicatedIDs(container) {


var $container  = container ? $(container) : $('body'),
elements = {},
duplicatedIDs = 0;
totalIDs = 0;


$container.find('[ID]').each(function(){
var element = this;


if(elements[element.id]){
elements[element.id].push(element);
} else  {
elements[element.id] = [element];
}
totalIDs += 1;


});


for( var k in elements ){
if(elements[k].length > 1){
console.warn('######################################')
console.warn('        ' + k )
console.warn('######################################')
console.log(elements[k]);
console.log('---------------------------------------');
duplicatedIDs += elements[k].length
}
}
console.info('totalIDs', totalIDs);
console.error('duplicatedIDs', duplicatedIDs);
}


duplicatedIDs('#element'); //find duplicated ids under that element
duplicatedIDs(); // entire page

You can use this solution which will print out in console a list of duplicate ids if any is present.

You can run the code directly in console (copy/paste) after you DOM is loaded and does not require additional dependence like jQuery.

You could use it to quickly found out possible errors in your HTML markup.

    (function (document) {
var elms = document.body.querySelectorAll('*[id]'),
ids = [];
for (var i = 0, len = elms.length; i < len; i++) {
if (ids.indexOf(elms[i].id) === -1) {
ids.push(elms[i].id);
} else {
console.log('Multiple IDs #' + elms[i].id);
}
}
})(document);

An example:

https://jsbin.com/cigusegube/edit?html,console,output

(here code is added before closing the body tag)

The top jQuery answer, rewritten in ES6:

  [...document.querySelectorAll('[id]')].forEach(el => {
const dups = document.querySelectorAll(`[id="${el.id}"]`);


if (dups[1] === el) {
console.error(`Duplicate IDs #${el.id}`, ...dups);
}
});

We can directly paste the below script into browser console to get duplicate IDs

[...document.querySelectorAll('[id]')].filter(el => [...document.querySelectorAll('[id]')].map(el => el.id).filter(id => id === el.id).length > 1);

Reference: https://www.abeautifulsite.net/getting-duplicate-ids-in-an-html-document