user756659 user756659 - 1 month ago 8
jQuery Question

jquery - selecting class with specific data-attribute value

Having a bit of a dumb moment right now and can't figure out why this is not working. It's been awhile since doing anything with jquery.

var owl = $('.owl-main');
var button = $('.owl-button');

owl.owlCarousel({
dots:false,
margin:15,
nav:true,
navText: [
'<span class="o-page">Prev</span>',
'<span class="o-page">Next</span>'
],
responsive:{
0:{
items:1
}
},
onChanged: callback
})

function callback(event) {
console.log(event.item.index);
console.log(button);

button.removeClass('active');
//$(".owl-button[data-id='"+event.item.index+"']").addClass('active');
button.find("[data-id='" + event.item.index + "']").addClass('active');
}


My issue is
button.find("[data-id='" + event.item.index + "']").addClass('active');
does not add the 'active' class yet the commented out code above it,
$(".owl-button[data-id='"+event.item.index+"']").addClass('active');
works perfectly fine.

button
and
event.item.index
are reporting correctly so why is that particular line doing nothing for me?

Answer

The issue is find() .. You are using it the wrong way.. it will actually search for the child element within the button with the given attribute. But what you want is to find a button with the given attribute.

  • The commented code is the way you have to do it.

Edit: If you want to use the stored array of button itself to get this working then you can use filter() in place of find

Here is a reference http://api.jquery.com/filter/

button.filter("[data-id='" + event.item.index + "']").addClass('active');