Why is it considered wrong/bad to repeat an HTML ID?

Asked

Viewed 1,712 times

19

I think the title says it all, why is it considered wrong to repeat HTML Ids?

I notice a lot of people doing things like:

<div id="foo">bar</div>
<div id="foo">baz</div>

To apply CSS and understand the problems this causes when selecting the element, but I would like an explanation with references and about the "semantics" of this, to better formulate the doubts:

  • This hampers the CSS?
  • This disturbs the Javascript?
  • Being language-independent, this hampers DOM or DOM manipulation as to the use of Apis (or libraries, regardless of whether it is front-end or other languages it has the ability to manipulate)?
  • Is there any time in HTML that ID would have the exception of being able to repeat itself?

Please cite examples of the problems so that it can become easier to endenter

  • 2

    Well, looking at the Javascript point of view, where we have the function called document.getElementById() that returns only one element when we make this call, you can get the idea that the idea of id is to be a reference to a single element. Now, the question is very interesting. We have all learned that you can only use one id, but we don’t usually know how to explain "Why"

  • Related or linked may be dup: https://answall.com/q/170451/101

  • @Maniero to which you replied, about ID and NAME, would probably serve as dup, but would like to keep to have something more objective within the behavior of DOM and "outside" of it, kind about HTML being permissive, but still things break, I will wait for the answers, if it doesn’t go beyond what you’ve already said there I think I’ll consider as dup even, I have an idea formed in my head, but it still doesn’t go very far.

  • 2

    Finally! Now I will be able to mark several ID questions as duplicates!

3 answers

25

Because the purpose of id is to be a unique identifier for the HTML element where it is applied. If he is not unique, this goes against the idea for which he was conceived, and it makes no sense to talk about exceptions that might allow it. If you want to use an identifier that can apply to several different elements simultaneously, use the attribute class.

However, this doesn’t get in the way of CSS (but I wouldn’t trust it):

#teste {
    color: red;
}
<div id="teste">Teste 1</div>
<div id="teste">Teste 2</div>
<div id="outro">Teste 3</div>

Already in Javascript, disturbs:

// Ok
document.getElementById("outro").style="color:blue";

// Só pega o primeiro elemento "teste".
document.getElementById("teste").style="color:red";
<div id="teste">Teste 1</div>
<div id="teste">Teste 2</div>
<div id="outro">Teste 3</div>

The same goes for jQuery:

// Ok
$("#outro").css("color", "blue");

// Só pega o primeiro elemento "teste".
$("#teste").css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="teste">Teste 1</div>
<div id="teste">Teste 2</div>
<div id="outro">Teste 3</div>

If the id if it repeats, the correct one would be to use the attribute class:

// Com jQuery.
$(".outro").css("color", "blue");

// Sem jQuery.
var em = document.getElementsByClassName("teste");
em[0].style="color:red";
em[1].style="color:red";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="teste">Teste 1</div>
<div class="teste">Teste 2</div>
<div class="outro">Teste 3</div>
<div class="outro">Teste 4</div>

Hence, it is concluded that repeated ids disrupt DOM manipulation, even with a library like jQuery. And maybe (just maybe) doesn’t mess with CSS.

In other programming languages that are able to manipulate the DOM, it will probably go wrong as well. Proof of this is that in Java, for example, the return type of method Document.getElementById(String) is Element instead of a NodeList, or be a single element. Expect this or similar behavior in all other DOM implementations in all other programming languages. None of them will know how to deal with ids duplicated.

  • Don’t forget that although it works on some browsers in some cases, as you put it well, it’s still wrong - and therefore nothing guarantees that the cases that work now on Chrome and firefox will work on all browsers, or even on those browsers in the future.

  • @jsbueno Well noted. Edited response.

15

It’s wrong because it’s in HTML specification that the ID must be unique. (Even, if you look at the linked document, which is the official specification of HTML 5, the English word "must" is used - which is "must" in the sense of actually being required).

The fact that repeated ID works with some things in some browsers does not make its use more correct: browsers have historically developed tolerance to some inaccuracies in HTML, perhaps because mainly during the 1990s, there was a lot of bad quality HTML generated by applications (with dozens of tags <font ...> intercalated, etc...). It is likely that this tolerance to duplicate Ids arose at this time.

So, it’s a bad idea to use equal ID because even if it works in some cases, first, the DOM Apis that use ID were not made for this: if there are two elements on the same page with the same ID, which of the two should be returned by document.getElementByID?

If you need equal identifiers for more than one element, that’s what the attribute is for name (and, you see, in this case the call is getElementsByName - plural, and returns an array of elements).

It is important to keep in mind that the name can also be used in CSS selectors. The "class" and "id" attributes, as we know, have unique operators in the CSS selector (. and #, respectively), but any HTML tag attribute can be used in the selector: the syntax is to place the attribute using brackets ('[' and ']') after the name of the html element. So if you want to change the background color of various "div"s with the attribute name="foo" for yellow, can do:

div[name="foo"] {background: #ffff00;}
<div name="foo">bar</div>
<div name="snafu">zort</div>
<div name="foo">baz</div>

  • 1

    The value must be Unique amongst all the Ids in the element’s home subtree, the latter part does not define that it should be unique in subtree only?

  • 4

    The "home subtree" there is a link - just click there to see his definition: "A Node’s home subtree is the subtree Rooted at that Node’s root element. When a Node is in a Document, its home subtree is that Document’s Tree." - i.e.: no - home subtree is the entire document - the exception may be only DOM snippets dynamically created in Javascript, but not yet associated with document window.

14

In my view it also disturbs in HTML, if you use internal anchors in the page is usually used href="#link" and in the element that will be anchored the id="link".

If you use the id="link" in various elements its anchor will never be correct, because it will not know to which element you really want to do the anchoring.

Notice that having two anchors bobbing for the same id they will always point to the first id

<a href="#link">menu 1</a>
<a href="#link">menu 2</a>

<div id="link" style="margin-top: 100vh">div menu 1</div>
<div id="link" style="margin-top: 200vh">div menu 2</div>

The same happens when using the attribute of label for="meu-btn" and in the input the id="meu-btn" Notice that by clicking on label she just marks the first checkbox, for the two of them having the same id and the labels point to the same place.

<label for="meu-btn">label1 btn1</label><br><br>
<label for="meu-btn">label2 btn2</label><br><br>
<input id="meu-btn" type="checkbox">btn1<br>
<input id="meu-btn" type="checkbox">btn2

Another example with label making it to a list <select>. Notice I try the same id independent of label the foco is always on the same list

  <label for="lista">Lista 1</label>
  <select id="lista">
    <option>Maria</option>
    <option>José</option>
    <option>João</option>
  </select>
  
  <label for="lista">Lista 2</label>
  <select id="lista">
    <option>123</option>
    <option>345</option>
    <option>789</option>
  </select>

When speaking of semantics and accessibility the element label is fundamental, so its correct functioning is essential, so it is important to be used in the correct way always linking label and focal element (https://www.w3.org/WAI/tutorials/forms/labels/)

Importance of Ids in the SVG and the accessibility

According to the W3C specification, we should do nothing additional for Svgs other than provide the <title> and possibly a <desc> because they should be available for the accessibility API. Unfortunately, browser support is not yet complete (there are bugs reported for Chrome and Firefox for example).

So, to ensure that the person can access the <title> and <desc>:

Add the IDs appropriate to the <title> and <desc>:

  • <title id = "uniqueTitleID"> The title of the SVG </ title>
  • <desc id = "uniqueDescID"> A longer and more complete description for complex graphics. </ desc>

For this we need unique Ids as the example below:

<svg id="cat"aria-labelledby="catTitle catDesc" role="img">
  <title id="catTitle">Título da figura</title>
  <desc id="catDesc">Descrição completa do elemento etc.</desc>
  <path d="M545.9,695.9c8.........."/>
</svg>

Source: https://css-tricks.com/accessible-svgs/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.