Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide all elements except the given data-* attribute with jQuery

I'm making a menu if someone clicks on one object it should filter all of them accordingly (i.e: all projects, completed projects a.s.o. I have a jQuery to take care of this like this (I added the .not() recently, before adding it this script worked):

$("#completed").click(function(){
 $('.project_wrapper[data-category="completed_projects"]').not(this).hide();
});

I have figured out that I should use .not() to .hide all objects that don't have the given [data-category] or am I doing this wrong?


Edit

The HTML:

The Menu:

<ul class="project_menu>
 <li id="complete">Completed Projects</li>
</ul>

The Projects:

<div class="project_wrapper" data-category="completed_projects">The projects</div>


Edit Got it working thanks to @Nitha & @Sam Hollenbach thanks!

Edited a bit myself but here is the final jQuery code I've got:

jQuery(document).ready(function($){

 // Show all
 $("#all").click(function(){
   $(".project_wrapper").show();
 });

 // Complete
 $("#complete").click(function(){
   $(".project_wrapper:not([data-category='completed_projects'])").hide();
   $(".project_wrapper[data-category='completed_projects']").show();
 });

});

Update

Instead of using .show and .hide I used .css("visibility", "collapse") & .css("visibility", "visible") show and hide seemed to bug out for me in WordPress.

like image 703
Krullmizter Avatar asked Aug 25 '26 00:08

Krullmizter


2 Answers

The below code will hide all the project_wrapper div with data-category not equal to "completed_projects" and will show the project_wrapper div with data-category equal to "completed_projects"

$(".project_wrapper:not([data-category='completed_projects'])").hide();
$(".project_wrapper[data-category='completed_projects']").show();
like image 90
Nitha Avatar answered Aug 27 '26 15:08

Nitha


I believe what you're asking is to hide all elements within .project_wrapper except for the .project_wrapper[data-category="completed_projects"] element. In that case I believe you can do this

$('.project_wrapper *').not('.project_wrapper[data-category="completed_projects"').hide()​;

Or if you want to remove everything in the body

$('body *').not('.project_wrapper[data-category="completed_projects"').hide()​;

This will remove all elements within .project_wrapper or body, subtract the one with the correct data-category, and then hide all the others.

Source

like image 37
Sam Hollenbach Avatar answered Aug 27 '26 15:08

Sam Hollenbach