0

My code:

$(".tags li").click(function() {
  var catid = $(this).data("catid");
  $("[data-category!="+ catid + "]").hide();
  $("[data-category="+ catid + "]").show();
});

jQuery documentation states that is better to use the .not() method. But how do I apply .not() to any element that has the data-category attribute?

5
  • 1
    $(".tags li").not("[data-category="+ catid + "]").show();? Commented Feb 22, 2018 at 2:13
  • No, the li has catid data attribute. I'm looking to hide any elements (div's, section's, etc.) with category data attribute. Commented Feb 22, 2018 at 2:14
  • share your HTML mark. its not clear to me what you mean Commented Feb 22, 2018 at 2:17
  • I can't. There's a whole bunch of elements with data-category. I need to hide those. Not the li's that have data-catid. Commented Feb 22, 2018 at 2:18
  • don't use data attributes as selectors, it is much slower than using classes. Commented Feb 22, 2018 at 3:15

1 Answer 1

1

not Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value. if i understand you correctly this will help you

$(".tags li").on("click", function() {
  var catid = $(this).data("catid");
  $("[data-category=" + catid + "]").show();
  $("[data-category]").not("[data-category=" + catid + "]").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tags">
  <li data-catid="1">Category 1</li>
  <li data-catid="2"> Category 2</li>
</ul>

  <div data-category="1">
    Category 1 Item
  </div>
  <div data-category="1">
    Category 1 Item
  </div>
  <div data-category="2">
    Category 2 Item
  </div>

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

2 Comments

It could, but there are many different parts of the page with data-category attribute. What I'm looking for is a simple snippet to hide those, without adding further markup to the page.
You can also make it work without changing any markup i had updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.