1

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

<a class="toggleArrow">Toggle Me</a>
<span class="arrow collapse" data-target="trgt1">
    <i class=fa fa-arrow-right""></i>
</span>

<span class="arrow collapse" data-target="trgt2">
    <i class=fa fa-arrow-left""></i>
</span>

JQuery is

$("a.toggleArrow").off().on("click", function () {
    $("span.arrow").each(function () {
        var dataTarget = $(this).data("target");
        if (dataTarget == "tgrt1") {
            dataTarget.toggleClass("collapse expand");
        }
    });
});

Can we use this way but it does not seem to work?

2 Answers 2

3

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");
});
Sign up to request clarification or add additional context in comments.

2 Comments

@Gags No, you're not, use $(this) to refer to the current element. Check update
yup.. this is fine. You are editing like anything :)
1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.