Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between $(element).find(".class").css(...) and $(this).css inside a $(element).find(".class").each() function?

If i want to edit CSS properties of a DOM element with a specific class using the jQuery find method, does it make a difference (in performance and browser compatibility) if i use this short way:

$(domobject).find(".theclass").css("color","#FFF");

or an each function like this:

$(domobject).find(".theclass").each(function() {
    $(this).css("color","#FFF");
});

In my case the dom-object is a backbone.js view.el element, but of course my question does not only apply to backbone.js.

Thanks for your help!

like image 448
Joe Hager Avatar asked Apr 12 '13 10:04

Joe Hager


2 Answers

So you want to style all your elements with the class "theclass"?

If so the jQuery Documentation for .each() says:

Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each() method

As Sirko suggested you could do a performance test :) I'd prefer your first choice

like image 185
SirDerpington Avatar answered Oct 22 '22 15:10

SirDerpington


Performance-wise, the first snippet is slighty faster:

enter image description here

Internally, it does pretty much the same thing, but the code to iterate over a set of elements inside jQuery is likely to be far more optimised than what you can achieve manually with .each.

As others have already stated, browser compatability should be identical.

like image 2
James Allardice Avatar answered Oct 22 '22 16:10

James Allardice