Skip to content Skip to sidebar Skip to footer

Toggle Class With Data-attribute

I am using Data attributes to get an element in jQuery as below Toggle Me

Solution 1:

Use $(this) to refer to the current element in the each. dataTarget is a string, you cannot call jQuery method on it dataTarget.toggleClass("collapse expand");

if ($(this).data('target') == 'tgrt1') {
    $(this).toggleClass("collapse expand");
    //^^^^^
}

No need of looping, use attribute-value selector to select all the <span> elements having class of arrow and data-target value as tgrt1.

$("a.toggleArrow").off().on("click", function() {
    $("span.arrow[data-target='tgrt1']").toggleClass("collapse expand");
});

Solution 2:

dataTarget variable contains string. You cannot use jQuery function onto a string.

dataTarget.toggleClass("collapse expand");

You need to replace with

$(this).toggleClass("collapse expand");

Post a Comment for "Toggle Class With Data-attribute"