JQuery 检查 DOM 中的重复 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/482763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:13:05  来源:igfitidea点击:

JQuery to check for duplicate ids in a DOM

jquerydom

提问by Simon_Weaver

I'm writing applications with ASP.NET MVC. In contrast to traditional ASP.NET you're a lot more responsible for creating all the ids in your generated page. ASP.NET would give you nasty, but unique ids.

我正在用 ASP.NET MVC 编写应用程序。与传统的 ASP.NET 相比,在生成的页面中创建所有 id 的责任要大得多。ASP.NET 会给您带来讨厌但唯一的 id。

I'd like to add a quick little jQuery script to check my document for duplicate ids. They may be ids for DIVS, images, checkboxes, buttons etc.

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

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

I'm looking for a set and forget type utility that'll just warn me when I do something careless.

我正在寻找一个设置并忘记类型的实用程序,当我做一些粗心的事情时它会警告我。

Yes i'd be using this only during testing, and alternatives (such as firebug plugins) are welcome too.

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

回答by sunsean

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

回答by Sjoerd

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

回答by AutoSponge

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

回答by Ionu? G. Stan

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

您应该尝试HTML Validator(Firefox 扩展)。它肯定会告诉您该页面具有重复的 ID 等等。

回答by Natrium

Why don't you just validate your html?

你为什么不验证你的html?

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

不允许使用双重 ID,通常会出现解析错误。

回答by Joshaven Potter

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

回答by Joshaven Potter

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

这可能会奏效它会提醒所有重复元素的 id。

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

回答by Burton

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

}

}

回答by GibboK

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

您可以使用此解决方案,它将在控制台中打印出重复 ID 列表(如果存在)。

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

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

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

您可以使用它来快速找出 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);

An example:

一个例子:

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

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

(here code is added before closing the bodytag)

(这里代码是在关闭body标签之前添加的)

回答by diegodafm

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

我创建了一个函数,您可以在其中检查特定元素以在页面内或整个页面中搜索重复的 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