Welcome to WebmasterWorld Guest from 107.22.14.254

Forum Moderators: not2easy

Message Too Old, No Replies

Difference between a class and an id

     
6:58 am on Feb 4, 2007 (gmt 0)

10+ Year Member



I know this is a really dumb question but what is the difference between

<div id="leftcol">
<div class="rightbox">

when does one use "id" and "class"?

7:36 am on Feb 4, 2007 (gmt 0)

5+ Year Member



Use class when you want the style to apply to one or more elements.
eg
<h1 class"boldblue">Some text</h1>
<p class="boldblue">some text</p>

Use id when you want to apply the style to only one element.
An id has to be unique in name and only one "unique id" per page.

8:56 am on Feb 4, 2007 (gmt 0)

10+ Year Member



Besides that ids must be unique on a page and classes can be repeated, there are a few other differences of note.
  • Ids have a higher level of specificity
  • An element can have multiple classes assigned to it (e.g. <p class="title quote"></p> can be selected by both .title{} and .quote{})
  • Ids on a form element with an id can be the target of a label element by assigning the label's "for" attribute the form element's id
  • Id's can be the target of a uri's hash: <a href="example.com/page.html#there">target page will be scrolled to element with the id of "there"</a>
  • There's a DOM method "getElementById()", but there's no "getElementsByClass()" (unless you write it yourself)
  • In style sheets, ids are prepended with a hash("#") while classes are prepended with a period(".")
10:07 am on Feb 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A couple of small additions to the above two points:

1) Id suggest using classes & ids to describe what some is, not what it looks like. So instead of <h1 class="bluebold"> do something like <h1 class="sectionhead">. That way when the client comes back next week and says Id like my blue & bold headings to be pink & italic itll make debugging easier in the future.

2) Mozilla recently added a (non-w3-standard) native implementation of getElementsByClassName [bugzilla.mozilla.org] to Gecko on the back of WHATWGs forthcoming Web Applications 1.0 [whatwg.org] spec.

[edited by: Robin_reala at 10:11 am (utc) on Feb. 4, 2007]

8:15 pm on Feb 4, 2007 (gmt 0)

10+ Year Member



Mozilla recently added a (non-w3-standard) native implementation of getElementsByClassName to Gecko

Good to know, thanks. I didn't notice if it said when they will be releasing it; do you know? I wonder why it wasn't part of DOM2?
10:02 pm on Feb 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, its in current Firefox trunk builds if you want to experiment. First major release itll appear in is Firefox 3.0.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month