Search code examples
htmlmarkup

Why is there such a thing as an id if you can just have classes with only one element?


From a language-design standpoint, what's the point of creating the id attribute for HTML if you can have a class with only one element? Why not just use classes for everything and not complicate the markup?

I can think of three possible explanations, but they don't fully satisfy me, so I wondered if you know why id was included in HTML. My thoughts are:

  1. The existence of an id helps in creating CSS styles because its greater specificity makes it possible to give an id to one member of a class overriding styles given to other members of that class. This explanation doesn't fully satisfy me because you could just give it an extra class instead and put the styles for that class at the bottom of the stylesheet in a section for styles given to single elements.
  2. When selecting elements with jQuery, the DOM traversal could stop as soon as the element with that id is found. Thus, the existence of an id would make the selection run faster. This explanation doesn't satisfy me because I'm fairly certain that jQuery was created long after ids and classes already existed.
  3. Having an id as a language feature could help to ensure that styles (and selectors) which are supposed to be unique truly are applied to only one element because things go haywire when this isn't the case. This explanation doesn't satisfy me because having your site break when you accidentally create two elements with the same id doesn't seem to be a particularly effective way of informing you that something's gone wrong.

Solution

  • The first publicly available description of HTML was a document called "HTML Tags", first mentioned on the Internet by Berners-Lee in late 1991.

    There is a description of anchor tag:

    <A NAME=xxx HREF=XXX> ... </A>
    
    HREF
    ...This allows for the form HREF=#identifier to
    refer to another anchor in the same document.
    NAME
    The attribute NAME allows the anchor to be the destination of a link.
    

    I think NAME attribute here is the predecessor of element's ID: it allowed you to link directly to a desired part of a hypertext page (even if it is the same page).