Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make jquery procedure run better

Tags:

jquery

I have the following code:

$('#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
});

It seems I'm using the $('#MyDiv .TheClass').eq(TheIndex) line several times; how can I make this better?

I thought of doing

var TheDiv = $('#MyDiv .TheClass').eq(TheIndex);

TheDiv.removeClass('ClassA');
TheDiv.removeClass('ClassB');
TheDiv.addClass('ClassC');

TheDiv.children().each(function () {
 //do something here
});

But I'm wondering if there's a better suggestion out there.

Thanks.

like image 820
frenchie Avatar asked May 10 '26 16:05

frenchie


1 Answers

jQuery provides a fluent interface [Wikipedia] with most of its methods:

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

If you are sure that the element has the classes ClassA and ClassB and needs ClassC, you can use .toggleClass() [docs]:

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

Though not necessarily relevant for your case, but if you wanted to chain more methods after the each loop, the following methods would apply to the selected children. If you want to select the original element again ($('#MyDiv .TheClass').eq(TheIndex)) you can go "one step back" in the chain by using .end() [docs].

like image 89
Felix Kling Avatar answered May 13 '26 07:05

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!