Reputation: 1779
I'm trying to show all elements which have a certain data- attribute set to a specific value and then hide all other elements with the same data- attribute but with a different value.
The code I have seems to hide all elements whether they have the data- attribute or not.
$('*').filter(function() {return $(this).data(dataAttr) == dataVal;}).show();
$('*').filter(function () { return $(this).data(dataAttr) !== dataVal; }).hide();
I need this to be dynamic as I am passing in the name of the data- attribute and the value to match.
Upvotes: 0
Views: 613
Reputation: 817128
The code I have seems to hide all elements whether they have the data- attribute or not.
That's because you are selecting all elements with '*'
. If the elements don't even have such an attribute, you are comparing undefined
against the value (undefined !== someValue
) is probably always true
.
Select all elements having the attribute first, hide them and then show the ones with a specific value:
$('[' + dataAttr + ']').hide()
.filter('[' + dataAttr + '="' + dataVal + '"]').show();
I decided to use selectors here because I believe that using .filter
and .data
will be much slower.
Upvotes: 1