0

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();
3
  • Use filter() instead of a data selector, which will result in a dom scan. Otherwise you could try using :not([...]) Commented Dec 6, 2016 at 17:52
  • $('[data-department !='+dept+']') will match many elements even the ones which don't have any data-department attribute... e.g html, body, etc... You'd have better to filter it using: $('[data-department]').filter('[data-department !='+dept+']').closest(...) Commented Dec 6, 2016 at 17:57
  • Let me restate the data selector warning. Regardless of if you use filter or not, doing simply $('[...]') should be avoided due to performance issues. Using purely attribute selectors, the browser has no way to scope the elements it needs to evaluate down and will check them all. This is the majority of the time unnecessary work. Which is why if you are going to use attribute selectors you should reduce the scope first so that the browser is only performing the comparison on as small of a subset as possible. Commented Dec 6, 2016 at 18:14

1 Answer 1

1

$('[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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.