JQuery - fetch value data-attribute when active class
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>