IT

요소가 다른 여러 HTML 요소가 동일한 ID를 가질 수 있습니까?

lottoking 2020. 7. 7. 07:25
반응형

요소가 다른 여러 HTML 요소가 동일한 ID를 가질 수 있습니까?


이와 같은 시나리오가 유효합니까? :

div#foo
span#foo
a#foo

아니.

요소 ID는 전체 문서 내에서 고유해야합니다.


나는 무언가가 독특해야하는지 아니면 독특해야하는지 (즉, 웹 브라우저에 의해 시행되어야 함)에 차이가 있다고 생각합니다.

ID는 고유해야합니까? 예.

ID는 고유해야합니까? 아니요, 적어도 IE와 FireFox는 여러 요소가 동일한 ID를 가질 수 있도록합니다.


여러 요소가 동일한 ID를 가질 수 있습니까?

예-태그가 같은지 여부에 관계없이 여러 요소가 동일한 ID를 가진 경우에도 브라우저는 페이지를 렌더링합니다.

유효한 HTML입니까?

아니요 . HTML 5.1 사양 에서는 여전히 그렇습니다 . 그러나 스펙은 또한 주어진 ID를 가진 첫 번째 요소를 getElementById 리턴해야 하므로 유효하지 않은 문서의 경우 동작이 정의되지 않도록합니다.

이 유형의 유효하지 않은 HTML의 결과는 무엇입니까?

(모든 경우) 대부분의 브라우저를 선택하고 여전히 않는 호출 주어진 ID를 가진 첫 번째 요소를 선택합니다 getElementById. ID로 요소를 찾는 대부분의 라이브러리는이 동작을 상속합니다. 대부분의 (모두는 아님) 브라우저는 또한 id-selector (예 :)로 지정된 스타일을 #myid지정된 ID를 가진 모든 요소에 적용합니다. 이것이 당신이 기대하고 의도하는 것이라면, 의도하지 않은 결과는 없습니다. 다른 것을 기대하거나 의도하지 않으면 (예를 들어 해당 ID를 가진 모든 요소가 반환되거나 스타일이 하나의 요소에만 적용되도록) 기대가 충족되지 않으며 해당 기대에 의존하는 기능이 실패합니다.

일부 자바 스크립트 라이브러리 여러 요소가 동일한 ID를 가질 때 충족되지 않을 것으로 예상합니다 ( d3.js에 대한 wootscootinboogie의 의견 참조 )

결론

코드가 현재 환경에서 예상대로 작동하고 이러한 ID가 예측 가능 / 유지 보수 가능한 방식으로 사용되는 것을 알고 있다면이를 수행하지 않는 두 가지 실용적인 이유가 있습니다.

  1. 여러 요소가 동일한 ID를 가질 때 사용자가 틀렸을 가능성을 피하기 위해 실제로 사용하는 라이브러리 중 하나 오작동합니다.
  2. 나중에 발생할 수있는 라이브러리 나 서비스 (또는 개발자!)와 웹 사이트 / 애플리케이션의 호환성을 유지하기 위해 여러 요소가 동일한 ID를 가질 때 오작동이 발생합니다.

힘은 당신입니다!


요소의 유형이 다르더라도 심각한 문제가 발생할 수 있습니다 ...

동일한 ID를 가진 3 개의 버튼이 있다고 가정하십시오.

<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>

이제 버튼을 클릭 jQuery했을 때 어떤 작업을 수행하도록 코드를 설정했습니다 myid.

$(document).ready(function ()
{
    $("#myid").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interestingFunction();

        $('form').trigger('submit');
    });
});

당신은 무엇을 기대합니까? 클릭 한 모든 버튼은 jQuery로 클릭 이벤트 핸들러 설정을 실행합니다. 불행히도 그것은 일어나지 않을 것입니다. 첫 번째 버튼 클릭 핸들러를 호출합니다. 클릭 할 때 다른 2는 아무것도하지 않습니다. 마치 버튼이 아닌 것처럼 보입니다!

따라서 항상 요소에 다른 IDs것을 지정하십시오 HTML. 이것은 이상한 것들로부터 당신을 덮을 것입니다. :)

<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>

Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS class applied to them like this:

$(document).ready(function ()
{
    $(".mybtn").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interstingFunction();

        $('form').trigger('submit');
    });
});

No. two elements with the same id are not valid. IDs are unique, if you wish to do something like that, use a class. Don't forget that elements can have multiple classes by using a space as a delimeter:

<div class="myclass sexy"></div>

The official spec for HTML states that id tags must be unique AND the official spec also states that if the render can be completed, it must (i.e. there are no such thing as "errors" in HTML, only "invalid" HTML). So, the following is how id tags actually work in practice. They are all invalid, but still work:

This:

<div id="unique">One</div>
<div id="unique">Two</div>

Renders fine in all browsers. However, document.getElementById only returns an object, not an array; you will only ever be able to select the first div via an id tag. If you were to change the id of the first div using JavaScript, the second ID would then be accessible with document.getElementById (tested on Chrome, FireFox & IE11). You can still select the div using other selection methods, and it's id property will be returned correctly.

Please note this above issue opens a potential security vulnerability in sites that render SVG images, as SVGs are allowed to contain DOM elements, and also id tags on them (allows script DOM redirects via uploaded images). As long as the SVG is positioned in the DOM before the element it replaces, the image will receive all JavaScript events meant for the other element.

This issue is currently not on anyone's radar as far as I know, yet it's real.

This:

<div id="unique" id="unique-also">One</div>

Also renders fine in all browsers. However, only the first id you define this way is utilized, if you tried document.getElementById('unique-also'); in the above example, you would be returned null (tested on Chrome, FireFox & IE11).

This:

<div id="unique unique-two">Two</div>

Also renders fine in all browsers, however, unlike class tags that can be separated by a space, the id tag allows spaces, so the id of the above element is actually "unique unique-two", and asking the dom for "unique" or "unique-two" in isolation returns null unless otherwise defined elsewhere in the DOM (tested on Chrome, FireFox & IE11).


SLaks answer is correct, but as an addendum note that the x/html specs specify that all ids must be unique within a (single) html document. Although it's not exactly what the op asked, there could be valid instances where the same id is attached to different entities across multiple pages.

Example:

(served to modern browsers) article#main-content {styled one way}
(served to legacy) div#main-content {styled another way}

Probably an antipattern though. Just leaving here as a devil's advocate point.


And for what it's worth, on Chrome 26.0.1410.65, Firefox 19.0.2, and Safari 6.0.3 at least, if you have multiple elements with the same ID, jquery selectors (at least) will return the first element with that ID.

e.g.

<div id="one">first text for one</div>
<div id="one">second text for one</div>

and

alert($('#one').size());

See http://jsfiddle.net/RuysX/ for a test.


Well, using the HTML validator at w3.org, specific to HTML5, IDs must be unique

Consider the following...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">Barry</div>
        <div id="x">was</div>
        <div id="x">here</div>
    </body>
</html>

the validator responds with ...

Line 9, Column 14: Duplicate ID x.      <div id="x">was</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>
Error Line 10, Column 14: Duplicate ID x.       <div id="x">here</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>

... but the OP specifically stated - what about different element types. So consider the following HTML...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">barry
            <span id="x">was here</span>
        </div>
    </body>
</html>

... the result from the validator is...

Line 9, Column 16: Duplicate ID x.          <span id="x">was here</span>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">barry

Conclusion:

In either case (same element type, or different element type), if the id is used more than once it is not considered valid HTML5.


Nope, IDs have to be unique. You can use classes for that purpose

<div class="a" /><div class="a b" /><span class="a" />

div.a {font: ...;}
/* or just: */
.a {prop: value;}

Is it possible to have more than one student in a class having same Roll/Id no? In HTMLid attribute is like so. You may use same class for them. e.g:

<div class="a b c"></div>
<div class="a b c d"></div>

And so on.


I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose


Usually, it is better not to use same ID multiple times in a html page. Even so, it is possible to use same ID many times in a page. However when you use an ID as a part of URI/URL as below:

https://en.wikipedia.org/wiki/FIFA_World_Cup#2015_FIFA_corruption_case

And if the ID('2015_FIFA_corruption_case') is used for only one (span)element in web page:

<span class="mw-headline" id="2015_FIFA_corruption_case">2015 FIFA corruption case</span>

There would be no problem. On the contrary, same ID exists in more than one place, the browser would be confused.


<div id="one">first text for one</div>
<div id="one">second text for one</div>

var ids = document.getElementById('one');

ids contain only first div element. So even if there are multiple elements with the same id, the document object will return only first match.

참고URL : https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme

반응형