Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select by class VS select by attribute

I want just to ask for an opinion of perfomance: Is it faster selecting elements by class name or by attribute name with jquery? Example I have 100 DIVs element in this form:

<div class="normal_box" normal_box=1>...</div> 

Which is faster:

$('div.normal_box').each(function(){...}); 

VS

$('div[normal_box=1]').each(function(){...}); 

I made some experiments on 30 divs but I don't see any difference with (new Date).getTime(); Maybe selecting by class is more efficient on CPU usage?

like image 729
albanx Avatar asked Jun 30 '11 10:06

albanx


People also ask

Which jQuery selector is fastest?

ID and Element selector are the fastest selectors in jQuery.

Which is faster jQuery (# id or jQuery div id?

$("#myId) The document. getElementbyId( "myId") is faster because its direct call to JavaScript engine. jQuery is a wrapper that normalizes DOM manipulation in a way that works consistently in every major browser.

What is the correct way of selecting the current element with jQuery selectors?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


1 Answers

this is a great post for exactly what you are looking for.

JQUERY SELECTOR PERFORMANCE TESTING

I've also found a great article that may help you on this topic:

  • some jquery selectors performance tests

let me know if this answer really helped you, thanks.

update: I've managed to make a sample to match your posted case, here are the results for a total set of 203 divs:

1- by using tag name having certine class name $("div.normal_box") ==> 884 ms

2- by using attribute value $("div[normal_box=1]") ==> 4553 ms

Update 2: I tried even further more than your question, and made it to test a few selectors, here is the new link for this updated test: http://jsfiddle.net/8Knxk/4/

3- by using tag name $("div") ==> 666 ms

4- by using just the class name $(".normal_box") ==> 762 ms

I think it's now more clear for you :)

like image 60
Mohammed Swillam Avatar answered Sep 17 '22 19:09

Mohammed Swillam