LeBlaireau
LeBlaireau

Reputation: 17467

Jquery not data selector

This works

  $('[data-department='+dept+']').closest('.person').hide();

So would expect this to show/hide the unselected elements.

$('[data-department !='+dept+']').closest('.person').hide();

It does not work as expected. Even when hard-coded.

$('[data-department!=8]').closest('.person').hide();

Upvotes: 0

Views: 413

Answers (1)

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

$('[data-department !='+dept+']') will select the elements even those which doesn't have any data-department attribute as A. Wolff said. So you can use filter() method like following.

$('[data-department]').filter(function() {
    return $(this).data('department') != 8;
}).closest('.person').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="person">
    <div data-department="8">
      8888888888888888
    </div>
</div>
<div class="person">
    <div data-department="9">
      9999999999999999
    </div>
</div>
<div class="person">
    <div data-department="10">
      1010101010101010
    </div>
</div>

Upvotes: 1

Related Questions