JQuery检查DOM中的重复ID

我用ASP.NET MVC编写应用程序。 与传统的ASP.NET相反,您需要在生成的页面中创build所有ID。 ASP.NET会给你讨厌但唯一的ID。

我想添加一个快速的小jQuery脚本来检查我的文档重复的ID。 他们可能是DIVS的ID,图像,checkbox,button等。

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

我正在寻找一个设置和忘记types的工具,只是当我做一些粗心的事情时,会警告我。

是的,我只会在testing期间使用它,并且也欢迎替代品(如firebug插件)。

以下内容将向控制台logging警告:

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

这个版本有点快,你可以将它复制到一个书签button,使它成为一个书签。

 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'); })(); 

您应该尝试HTMLvalidation器 (Firefox扩展)。 它一定会告诉你页面有重复ID和更多。

我有一个大页面,所以脚本运行速度太慢,以至于无法完成(多个“继续脚本”消息)。 这工作正常。

 (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); } } } }()); 

你为什么不只是validation你的HTML?

双ID是不允许的,通常你会得到一个分析错误。

另一种查找重复的方式,但是这将添加一个类的错误,所以它会有红色的文字:

 // 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>'); } 

这可能会诀窍它会提醒重复所有元素的ID。

 <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> 

我喜欢这个,因为它将实际元素吐出到控制台。 它可以更容易地调查正在发生的事情。

 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."; 

}

我创build了一个函数,你可以检查一个特定的元素在整个页面内search重复的id:

 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 

您可以使用这个解决scheme,如果有的话,将在控制台中打印出重复ID列表。

您可以在加载DOM后直接在控制台(复制/粘贴)中运行代码,并且不需要额外的依赖,如jQuery。

您可以使用它来快速找出HTML标记中可能出现的错误。

  (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); 

一个例子:

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

(在closuresbody标签之前添加代码)