views:

48

answers:

2

Hi everyone,

I was wondering which was the fastest way to apply a class on body and, let's say, all paragraphs. We can use simple selectors such as:

$("body").addClass("foo");
$("p").addClass("bar");

But also traversing methods like:

$("body").addClass("foo").find("p").addClass("bar");

Is there any difference in term of performance?

Cheers, Benjamin

A: 

If it was the same class you could try andSelf():

$("body").find("p").andSelf().addClass("bar");

With regard to performance, I wouldn't imagine there was much difference, if any in your examples.

James Wiseman
That really wouldn't work, the same as the code in question? He wants to add a different classes for body and paragraph elements. Your code adds the same class to both element types.
RaYell
+2  A: 

I would suspect second version to be slightly faster because find will look for the elements matching selector among the children of the previous selector results. However in this case the difference will probably be so small that you won't even notice it.

RaYell
you mean "the difference will be so *small*", right?
Yonatan Karni
Yeah, fixed the typo :)
RaYell
Thanks for your answer, RaYell, that's what I thought ;)
bendc