4

Why would you use "div class" instead of "div id"

Usually when I name a div I use "id" to give a name to an element and with set parameters. I really only use "class" to give it special characteristics. For my example .

However, I have a professor who will "class" to identify all his divs. For example prof example .

Can someone explain the benefit of something like "div class" instead of "div id".

Mouse
  • 51
  • 1
  • 4

3 Answers3

2

If you are using Javascript there is a big advantage of using classnames to identify elements instead of id's.

Giving an id to an element also creates a global javascript variable with the same name. See Do DOM tree elements with ids become global variables? for more about that behaviour.

Having such implicitly created variables is at best confusing, and at worst leading to hard to find errors.

Community
  • 1
  • 1
MikaelE
  • 85
  • 7
1

ID are unique for the page, so it's better for identification. Class aren't unique and are supposed to be to group similar style things together.

Said otherwise, if you need to apply something to THAT SPECIFIC div, you should call it by the id, because it will take priority over other CSS styles that may affect it. Classes will allow you to set some common ground in your style so you can use similar fonts or sizes in different kind of elements.

LordNeo
  • 1,195
  • 1
  • 8
  • 21
1
<div class="some_class">

    <p>This can be used any number of times on one HTML page</p>

</div>

<div id="some_id">

    <p>This CAN be used multiple times with the same ID,
       but it is invalid code, as a specific ID should
       only be used ONCE per html page</p>

</div>

Here's an older yet still good explanation.

scoopzilla
  • 887
  • 5
  • 15