Reputation: 3829
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?
Upvotes: 1
Views: 3227
Reputation: 87203
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");
});
Upvotes: 3
Reputation: 1252
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");
Upvotes: 1