CSS - ID's and Classes

Soldato
Joined
18 Oct 2002
Posts
9,598
Location
Sunderland
Thats pretty much it, also you can give some meaning through using ids in you css - so if someone else sees a style defined for an id in your css, they know that that element should only appear once on a page.
 
Soldato
Joined
18 Oct 2002
Posts
5,464
Location
London Town
The nature of IDs as unique identifiers means they're also incredibly useful for interacting with specific elements of a page. Examples being (for an element with id "contact"):
  • Using a fragment identifier in a URL - www.example.com/details.htm#contact.
  • Accessing an element through the DOM with scripting - Javascript's getElementById('contact') function.
 
Soldato
Joined
26 Dec 2003
Posts
16,522
Location
London
Although don't feel obliged to litter your code with unnecessary IDs if you just want to access the elements via Javascript; instead, use something like Simon Willison's getElementsBySelector() to select the element(s) via a CSS selector. So, with the markup:

Code:
<div id="header">

<h1>Title</h1>

<ul>
    <li>lalala</li>
    <li><a href="#">lol</a></li>
</ul>

</div>

You don't need to add an otherwise unnecessary ID to the <ul> to access it via Javascript, you can access it just as you would with CSS:

Code:
var nav = document.getElementsBySelector('#header ul');

Leaner markup + unobtrusive Javascript = Lovely :)
 
Soldato
Joined
18 Oct 2002
Posts
5,464
Location
London Town
robmiller said:
Although don't feel obliged to litter your code with unnecessary IDs if you just want to access the elements via Javascript; instead, use something like Simon Willison's getElementsBySelector() to select the element(s) via a CSS selector.
While the function's great, it's got limited scope. With just descendant and attribute support, what happens if you have more than one list element and you want to only want to access one particular list - which do you pick out of the array? Or what happens when you move that particular list to a different part of the page?

If an element needs to be targeted, then use an ID, that is the purpose of the attribute. No point avoiding an ID for the sake of a few bytes. Personally I'd feel in many scenarios that the initial overhead of a 6KB+ script is worse than adding an ID where it's actually appropriate :).
 
Back
Top Bottom