-2

Lets assume you are making a brand new app. You get to make the view/template/CSS/JS however you like, there is nothing pre-defined, there is no structure. You can use whatever selector you desire, including classes/data-attribs, in all your helper libs.

So my question: What is the purpose of using ID's when classes/data-attribs are more flexible, reusable, and generally easier to "stack"? Assuming you are building everything from scratch, does anyone have a concise reason that an element ID would be absolutely needed? Why do we still insist on using them in code?

I see no point whatsoever to using an ID....ever. Quite frankly all they do is cause validators to yell at you for misusing them. Maybe i'm missing some golden egg and someone could enlighten me as to why we still use element ID's in our apps and things.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
dhaupin
  • 1,613
  • 2
  • 21
  • 24
  • 5
    `document.getElementById("idname")`, for one. – 9Deuce Apr 09 '15 at 19:26
  • 5
    Also, you can navigate to an ID by including it as a hash in the URL (and that ties in with the requirement that it has to be unique). You can't do this for classes. Navigating to different IDs/anchors also [trigger hash changes](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange), which can be tracked using JS—think of a multi-state but single-page website. – Terry Apr 09 '15 at 19:27

2 Answers2

3

id is less flexible than class. But that's its advantage, not its failing. When you give something an id rather than a class, you can rely on it being unique and unambiguous (if the document is valid). If you refer to the element in CSS or JavaScript, you know you're going to get a single element. Because of this, there are lots of functions and frameworks that rely on id (as the comments on your question indicate).

There's also a performance difference: it's faster to reference ids (because they're unique) than classes, because to find all the instances of a class you need to traverse the whole document. See this answer.

Community
  • 1
  • 1
ASGM
  • 11,051
  • 1
  • 32
  • 53
1

IDs can be used to semantically markup unique elements (for example sections documentation).

While classes have a flexibility in that they are many to one and can be used for general classification - IDs still have their unique use case.

One example is the the ability to be able to link to a specific paragraph in a document, or pagination.

That said, IDs have been widely abused since the beginning of web design due to the fact that the DOM has had pretty awful APIs for selecting elements by class - and the fact that ID based lookups have traditionally had much better performance.

max
  • 96,212
  • 14
  • 104
  • 165