DOM에서 중복 ID를 확인하는 JQuery


106

ASP.NET MVC로 응용 프로그램을 작성하고 있습니다. 기존 ASP.NET과 달리 생성 된 페이지에서 모든 ID를 만드는 데 훨씬 더 많은 책임이 있습니다. ASP.NET은 불쾌하지만 고유 한 ID를 제공합니다.

내 문서에서 중복 ID를 확인하기 위해 간단한 jQuery 스크립트를 추가하고 싶습니다. DIVS, 이미지, 체크 박스, 버튼 등의 ID 일 수 있습니다.

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

나는 부주의 한 일을 할 때 나에게 경고 할 세트를 찾고 있고 유형 유틸리티를 잊어 버립니다.

예, 테스트 중에 만 이것을 사용하고 있으며 대안 (예 : 방화 버그 플러그인)도 환영합니다.

답변:


214

다음은 콘솔에 경고를 기록합니다.

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

완전한! 감사! 이미 중복 ID가있는 세 곳을 발견했습니다. 이 문제에 대한 대부분의 사람들의 해결책이 'firebug'또는 'html validator'를 사용하는 것이라는 점에 약간 실망합니다. 충분하지 않습니다! 이상한 상황에서 예상치 못한 중복을 포착하고 싶습니다.
Simon_Weaver

4
도니는 다르게 그리고 난 : 난을 해결하기 위해 그래서 (...) 경고에 console.warn 전환
Simon_Weaver

이것은 매우 유용하고 가치가 있음을 발견했습니다. 내가 그것을 프레임 워크의 표준이되어야한다고 생각 - 특히 디버깅시
Simon_Weaver

6
작업이 필요한 DOM 순회의 양은 꽤 놀랍다
조쉬 Stodola

8
매우 좋은 솔루션이지만 추가 따옴표가 필요 var ids = $('[id=\''+this.id+'\']');하므로 ID의 점 및 기타 이상한 것들과 함께 작동합니다.
zidarsk8 2014 년

33

이 버전은 다소 빠르며 북마크 버튼에 복사하여 북마크릿으로 만들 수 있습니다.

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

3
이 알고리즘은 더 좋으며 일치하는 요소 당 하나가 아니라 하나의 dom 순회 만 필요합니다. 받아 들여진 대답이어야합니다.
m_x 2015

1
name = id로 입력 된 양식에 대해 오탐을 제공합니다. javascript:(function () { var ids = {}; var found = false; $('[id]').each(function() { var id = this.getAttribute('id'); if (id && ids[id]) { found = true; console.warn('Duplicate ID #'+id); } ids[id] = 1; }); if (!found) console.log('No duplicate IDs found'); })(); 더 좋을 것입니다.
alpo

14

큰 페이지가있어서 스크립트가 너무 느리게 실행되어 완료 할 수 없습니다 (여러 개의 "스크립트 계속"메시지). 이것은 잘 작동합니다.

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

큰! 감사. 나는 종종 이것을 프로덕션에서 실행하고 있다는 것을 잊고 지금까지 그것을 최적화해야합니다-또는 디버그 설정을 추가하여 켜거나 끄십시오!
Simon_Weaver 2011 년

저는 다른 구성으로 스크립트를 결합하기 위해 끊임없이 노력하고 있으며 이것은 확실히 저에게 많은 도움이 될 것입니다. 감사합니다 :)
Andy Gee

일반 자바 스크립트 솔루션의 경우 +1. 중복 된 ID를 찾은 후 $x("//*[@id='duplicated-id']")콘솔에서 XPath 표현식 ( )을 사용하여 중복 된 ID가있는 요소를 쿼리했습니다.
cassiomolin 2015 년


8

HTML의 유효성을 검사하지 않는 이유는 무엇입니까?

이중 ID는 허용되지 않으며 일반적으로 구문 분석 오류가 발생합니다.


2
이를 위해 어떤 옵션이 있습니까?
Simon_Weaver

또한 FF에서는 유효성 검사기가있는 도구 아래의 웹 개발자 도구 모음을 사용하십시오
IEnumerator

4
jquery ui의 대화 상자와 같은 위젯으로 작업 할 때 대화 상자를 만든 후 정리하지 않을 때 DOM에서 중복으로 끝나는 경우가 자주 발생합니다.
guido

4

중복을 찾는 또 다른 방법이지만 이것은 오류 클래스를 추가하므로 빨간색 텍스트가 표시됩니다.

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

멋지네요! 감사. 나는 실제로 원래 받아 들여진 대답이 귀중하다는 것을 발견했습니다. 너무 많은 것을 포착하고 아마도 시간을 절약했습니다!
Simon_Weaver

멋지지만 콘솔 기능 만 사용하고 나머지는 그대로 두지 않는 이유는 무엇입니까? 논리 및 프리젠 테이션 등의 분리 등
Will Morgan

3

ES6로 다시 작성된 최상위 jQuery 답변 :

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

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

2

이것은 트릭을 할 수 있습니다. 중복 된 요소의 모든 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>


1

나는 이것이 콘솔에 실제 요소를 뱉어 내기 때문에 이것을 좋아한다. 무슨 일이 일어나고 있는지 조사하기가 더 쉽습니다.

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

}


이 기능은 새로운 HTML이 페이지에 추가 될 때 복제 된 ID를 감지 할 수 있었기 때문에 제안 된 Chrome 확장 HTML 유효성 검사기가 작동하지 않는 경우 매우 유용했습니다.
Giselle Serate

1

이 솔루션을 사용하면 중복 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

(여기에 body태그 를 닫기 전에 코드가 추가됨 )


0

페이지 내 또는 전체 페이지에서 중복 된 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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.