jQuery how to find an element based on a data-attribute value?
Solution 1:
You have to inject the value of current
into an Attribute Equals selector:
$("ul").find(`[data-slide='${current}']`)
For older JavaScript environments (ES5 and earlier):
$("ul").find("[data-slide='" + current + "']");
Solution 2:
in case you don't want to type all that, here's a shorter way to query by data attribute:
$("ul[data-slide='" + current +"']");
FYI: http://james.padolsey.com/javascript/a-better-data-selector-for-jquery/
Solution 3:
When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:
$('<b data-x="1">' ).is('[data-x=1]') // this works
> true
$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false
$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true
You can use this instead:
$.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
}
$('<b>').data('x', 1).filterByData('x', 1).length
> 1