yarek
yarek

Reputation: 12044

How to filter selector results by data attributes?

I want to show all users in

<div id="users>
    <div class="item" data-username="ity">ity</div>
    <div class="item" data-username="ity2">ity2</div>
    <div class="item" data-username="ity3">ity3</div>
    <div class="item" data-username="hello">hello</div>
</div>

My idea is simply to show/hide items whose data contains an username

ex: I want to show ALL divs that contains it so it should show 3 divs.

I tried with

$("div .item[data-username='it']").show();

The problem is it affects ONLY div elements whose data-username IS ity.

I also tried :contains

$("div .item[data-username:contains('it')]")

This is not good since it looks for the WHOLE div and not data-username ONLY the 4th div will be shown as well since it contains "item" inside

Any idea ?

Upvotes: 0

Views: 37

Answers (2)

Praveen
Praveen

Reputation: 236

Not sure if it is a typo but your id "users" is not closed making the html invalid.

You could use some regex style selectors as below

$('div.item[data-username^="it"]')

Upvotes: -1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use the 'attribute contains' selector:

$("div .item[data-username*='it']").show();

Or the 'attribute begins with' selector, depending on your requirements:

$("div .item[data-username^='it']").show();

Also note that filter() can be used too, although this will be slower than the above methods:

$('div .item').filter(function() {
    return $(this).data('username').indexOf('it') != -1;
}).show();

Upvotes: 2

Related Questions