- 22 days ago 5x
HTML Question

Using :data attribute as a selector to filter elements

I am trying to use a custom data attribute to filter things via dropdown selections. I can't seem to get the selector to work correctly, and was just wondering if that is actually possible. Currently looking at but I can't seem to get it to work.


<div class="item-filter">
<select id="item-filter-select">
<option value="all" id="all">Show All</option>
<option value="clothes" id="clothes">Clothing</option>
<option value="jewelry" id="jewelry">Jewelry</option>
<option value="misc" id="misc">Miscellaneous</option>

<div class="item-display" id="item-display">

<div class="item clothes" id="item-clothes" data-type="clothes" data-name="Sweater01" data-price="15">
<a href="#" class="add-item" id="item01">Add to Cart</a>

<div class="item jewelry" id="item-jewelry" data-type="jewelry" data-name="Necklace01" data-price="5">
<a href="#" class="add-item" id="item02">Add to Cart</a>

<div class="item misc" id="item-misc" data-type="misc" data-name="PhoneCase01" data-price="10">
<a href="#" class="add-item" id="item03">Add to Cart</a>

<div class="clear"></div>

My JS:

$( document ).ready(function() {
// Handler for .ready() called.

$('#item-filter-select').change(function() {

var clothes = $( "div:data(type, clothes)" );

if($(this).val() === 'clothes'){
console.log("You selected clothes");
else if($(this).val() === 'jewelry'){
console.log("You selected jewelry");
else if($(this).val() === 'misc'){
console.log("You selected miscellaneous");
else {
console.log("You are showing all");


I just want to hide the elements associated to the data type "selected" (I will eventually use the :not selector to hide elements that don't match) but for now I just need to get the selectors to work properly. Thank you for any help!


Just use the selects value directly to target the elements with the correct data attribute

$(document).ready(function () {
    $('#item-filter-select').on('change', function () {
        if (this.value == 'all') {
            var elems = $('.item[data-type="'+this.value+'"]');


or a shorter version of the above

$(document).ready(function () {
    $('#item-filter-select').on('change', function () {
        var elems = this.value == 'all' ? $('.item') : $('.item[data-type="'+this.value+'"]');