frenchie
frenchie

Reputation: 52037

is this jquery faster?

I used to write this:

$('#MyDiv .TheClass').eq(TheIndex).removeClass('ClassA');
$('#MyDiv .TheClass').eq(TheIndex).removeClass('ClassB');
$('#MyDiv .TheClass').eq(TheIndex).addClass('ClassC');

$('#MyDiv .TheClass').eq(TheIndex).children().each(function () {
 //do something here
});

and now I'm writing this:

$('#MyDiv .TheClass').eq(TheIndex)
  .removeClass('ClassA ClassB')
  .addClass('ClassC')
  .children().each(function () { 
      // do something here
  });

Is the latter going to run faster than the former? Just curious.

Upvotes: 0

Views: 51

Answers (3)

Steve Wellens
Steve Wellens

Reputation: 20640

Query after query will be slow and inefficient. Chaining is hard to read and harder to debug.

Here is another option:

   $MyDiv = $('#MyDiv .TheClass');

    $MyDiv.eq(TheIndex).removeClass('ClassA');
    $MyDiv.eq(TheIndex).removeClass('ClassB');
    $MyDiv.eq(TheIndex).addClass('ClassC');

Upvotes: 1

jli
jli

Reputation: 6623

You could try profiling it, however in this case the difference is fairly simple. In the first case, jQuery has to go and figure out what objects satisfy $('#MyDiv .TheClass') 4 times, whereas in the second case it only has to do that once, then simply passes the object to the next method. So yes, the second one is faster (not by much though).

Upvotes: 0

kazinix
kazinix

Reputation: 30153

One thing's for sure, this codes FINDS the element each line:

$('#MyDiv .TheClass').eq(TheIndex).removeClass('ClassA');
$('#MyDiv .TheClass').eq(TheIndex).removeClass('ClassB');
$('#MyDiv .TheClass').eq(TheIndex).addClass('ClassC');

In chaining, if finding the element is just once, it is faster then:

$('#MyDiv .TheClass').eq(TheIndex)
  .removeClass('ClassA ClassB')
  .addClass('ClassC')
  .children().each(function () { 
  // do something here
});

Upvotes: 1

Related Questions