I set the same id for two items. Why is the second painted?

 #red { color: red; } 
 <span id="red"> red </span> no red <span id="red"> red </span> 

2 answers 2

Because it is css. Theoretically, each element is checked for compliance with each selector. In this case, both elements of the selector approached.

Unlike js, where one element is issued on request, in css styles are applied to existing elements, rather than tracked, to how many elements this selector can be applied with the need to follow the appearance of such elements.

Well, yes, the markup is still invalid.

  • here js should probably be replaced with DOM . - teran
  • @teran, did not understand exactly how. - Qwertiy
  • the uniqueness of the selector is determined at the level of HTML DOM , and js can only work with the document model and in fact has no requirements for the uniqueness of identifiers. That is, by itself, js it has nothing to do with it at all. In this case, uniqueness is needed not in the whole document, but in a branch of a tree. - teran
  • @teran, in general, my idea of ​​the answer was that selectors are checked in css for each element, and corresponding elements are selected in js for the selector. By the way, I’m now using Chrome on querySelectorAll ('# red') gave everything, although in jQuery this wasn’t exactly the case before ... - Qwertiy
  • Yes, I understood your idea. It just turns out that there is HTML, which imposes the very limitations on the uniqueness and forms the document. And there are two tools - css , applying the rules of visual design, and js , allowing you to manipulate the structure. Therefore, talking about css and js , without affecting HTML, is somehow not entirely correct. - teran

In the case of CSS, the id behaves like a class, but in JavaScript it will be applied only to the first element:

 document.getElementById("red").style.color = "red"; 
 <span id="red"> red </span> no red <span id="red"> red </span> 

  • Um .. Is that the answer? - Qwertiy
  • @Qwertiy and what is it? - Vlad Gavriuk
  • 2
    @Qwertiy your answer is, in general, not very informative - teran
  • @teran, I tried to answer the question why. And here I see only a strange fact :) - Qwertiy