DOM Node Selection with CSS



CSSYesterday we looked at selecting DOM nodes via JavaScript. Today, we'll go over how to do the equivalent via CSS. Although CSS provides a much richer array of DOM node selection capabilities, for now we'll just tackle the basics.


Selecting a Single Unique Tag


The simplest situation is when you need to select a single unique tag from the page. You can do this by giving your tag an id attribute, and then using an id selector. See below.
<style type="text/css">
#MyDiv
{
    font-weight:bold;
}
</style>
<div id="MyDiv"></div>

A couple of notes about this; first of all, never ever assign the same id to multiple tags. This goes completely against what the id attribute is for-to uniquely identify a single tag. Secondly, it real-world scenarios, you're most likely to have your CSS in the head of the document, or included from the head of your document.

Selecting a Group of Tags with the Same Name


What if you wanted to select a group of tags though? What if, say, you wanted to select all div tags on your page? You can do this easily enough by using an element selector. See below.
<style type="text/css">
div
{
    font-weight:bold;
}
</style>
<div id="MyDiv"></div>


Selecting a Group of Tags


In the examples we've encountered so far, we've been able to select a single tag, and select a group of tags (as long as those tags had the same tag name). But what if we wanted to select a group of tags that had entirely different names? In that case, neither id selectors or element selectors are sufficient. Enter class selectors.
<style type="text/css">
.target
{
    font-weight:bold;
}
</style>
<div class="target"><span class="target"></span></div>


No comments :