I am trying to display the data-attribute when an anchor
tag has an active class in my console.log
unfortunately, It always outputs a null
value.
I referred to this stackoverflow question
here is my HTML:
$(document).ready(function () {
$('.list-group-item').on('click', function (e) {
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
var itemType = $('.list-group a').find('.active').data('itemtype');
console.log(itemType);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list-group">
<a href="#" class="list-group-item" data-itemtype="1">Cras justo odio</a>
<a href="#" class="list-group-item" data-itemtype="0">Dapibus ac facilisis in</a>
<a href="#" class="list-group-item" data-itemtype="3">Morbi leo risus</a>
<a href="#" class="list-group-item" data-itemtype="4">Porta ac consectetur ac</a>
<a href="#" class="list-group-item" data-itemtype="2">Vestibulum at eros</a>
</div>
please help me to be on track with the development.
Thank you in advance
As such finding "active"
class in the div having class list-group
so use $('.list-group').find('.active').data('itemtype')
selector in place of $('.list-group a').find('.active').data('itemtype')
.
Your selector $('.list-group a').find('.active').data('itemtype')
will try to find active
class in the a
tag of div with class list-group
which is making issue.
Please check working snippet.
$(document).ready(function () {
$('.list-group-item').on('click', function (e) {
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
var itemType = $('.list-group').find('.active').data('itemtype');
console.log(itemType);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group">
<a href="#" class="list-group-item" data-itemtype="1">Cras justo odio</a>
<a href="#" class="list-group-item" data-itemtype="0">Dapibus ac facilisis in</a>
<a href="#" class="list-group-item" data-itemtype="3">Morbi leo risus</a>
<a href="#" class="list-group-item" data-itemtype="4">Porta ac consectetur ac</a>
<a href="#" class="list-group-item" data-itemtype="2">Vestibulum at eros</a>
</div>
Try this one
$(document).ready(function () {
$('.list-group-item').on('click', function (e) {
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
var itemType = $('.list-group a').find('.active').attr('data-itemtype');
console.log(itemType);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With