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.
jQuery provides a fluent interface [Wikipedia] with most of its methods:
If you are sure that the element has the classes
ClassAandClassBand needsClassC, you can use.toggleClass()[docs]:Though not necessarily relevant for your case, but if you wanted to chain more methods after the
eachloop, 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].