Racso
Racso

Reputation: 2449

CSS and jQuery: .name vs name^= (i.e. classes vs "id arrays")

Consider the following three scenarios:

(1):

<div class="zones"></div>
<div class="zones"></div>
<div class="zones"></div>

vs (2):

<div id="zone1"></div>
<div id="zone2"></div>
<div id="zone3"></div>

vs (3):

<div id="zone1" class="zones"></div>
<div id="zone2" class="zones"></div>
<div id="zone3" class="zones"></div>

Given that you can target every <div> by using accordingly either the .zones or div[id^=zone] selectors (both in CSS and jQuery),

Is there any advantage of using (1) or (3) over (2)?

Upvotes: 1

Views: 158

Answers (2)

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

It completely depends on the situation.Personally I wouldnt care about saving those nanoseconds and would like to write a cleaner html that every developer understands (more class based because id can be used more while javascripting)

You can obviously write your entire html with class,tags,child + siblings selectors,nth-child.

just an example:

.mainclass > .innerclass > a{
cloro:red;
}

the same thing could be done if you assign id=something to a tag:

#something{
color:red;
}

use class:only when multiple dom elements share the same characteristic.

use Id's:only when different dom elements share unique characterictic.

But ultimately.it all comes down to writing cleaner,simpler and understandable codes.

Upvotes: 0

BoltClock
BoltClock

Reputation: 723498

The purpose of an ID is to uniquely identify an element. If you don't need to identify each element individually, there is no reason to give each one of them an ID. Likewise, if you don't need to associate the three elements with one another, there is no reason to assign them a common class name.

If you're going to go with option 3 because you need both IDs and classes, that's when you consider the difference between selectors.

In CSS, .zones is less specific than div[id^=zone] because of the missing type selector (a class selector and an attribute selector are equally specific by themselves). Of course, if you want to balance the specificity of both selectors, you can consider div.zones instead of .zones.

Class selectors are also usually optimized so they're far more straightforward to match, both in CSS and jQuery. The resultant difference in performance is not significant, but if you can match the exact same elements by class, there is no reason not to use a class selector over an attribute selector. Thus, again, if you're going to style or manipulate the three elements as a group, assign them a class name and select by that class.

Upvotes: 3

Related Questions