CSS/HTML : ID or CLASS attribute? Which one to use when ?

A simple, yet powerful classification of the DOM elements can done using the element attributes ID and CLASS. By giving a CLASS attribute, we can refer/select MULTIPLE elements with the same class. Example:

<div class="myclassA">first content</div>
<div class="myclassA">second content</div>
<div class="myclassA">third content</div>

Once we have such layout, we can access all the div's easily, some of them would be: 1. In the .CSS file as :

.myclassA{
 color : red;
}

2. If ur using JQuery:

$(".myclassA").css("color", "blue");

By giving a ID attribute, we can refer/select EXACTLY one element with that ID. Example:

<div id="myDivIdA">first content&lt;/div>
<div id="myDivIdB">second content</div>

Once we have such layout, we can access EXACTLY one div easily, some of them would be: 1. In the .CSS file as :

#myDivIdA{
 color : red;
}

2. If ur using JQuery:

$("#myDivIdB").css("color", "blue");

NOTE: 
When accessing, CLASS attributes are prefixed with '.'
and ID attributes are prefixed with '#'

Elements can have both CLASS and ID attributes. So you can can even more flexibility.

No comments:

Post a Comment

Python contextlib for Timing Python code

If you've ever found yourself needing to measure the execution time of specific portions of your Python code, the `contextlib` module o...