jrm
jrm

Reputation: 925

jQuery - show/hide DIVs is they have a certain class

Here is my code :

  <div id="principal" class="classxx">
    <div class="class001 cat2 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005"></div>
      </div>
    </div>
    <div class="class001 cat3 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005"></div>
      </div>
    </div>
    <div class="class001 cat1 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005"></div>
      </div>
    </div>
  </div>

I need a function like :

function showOnlyCat(className){}

If I call showOnlyCat('cat3') I want to see only all the DIVs that have the 'cat3' class (each DIV having multiple classes) and its children of course The function has to target only first children of DIV#principal

And I also need a showAllCat() that shows all the children DIVs of DIV#principal

Thank you VERY MUCH for your help

Upvotes: 1

Views: 2705

Answers (2)

Sayubu
Sayubu

Reputation: 33

hello with jQuery you can do that:

function showAllCat() {
    $('#principal div').each(function() {
        $(this).css('display', 'block');
    })
}

function showOnlyCat(className) {
    $('#principal div:not(.' + className + ')').each(function() {
        $(this).css('display', 'none');
    })

    $('#principal div.' + className).each(function() {
        $(this).css('display', 'block');
    })
}

//other way:
function showOnlyCat1(className) {
    //hide all
    $('#principal div').each(function() {
        $(this).css('display', 'none');
    })
    //showing only class parameter
    $('#principal div.' + className).each(function() {
        $(this).css('display', 'block');
    })
}

Upvotes: 0

Sylvain
Sylvain

Reputation: 1233

function showOnlyCat(className){
 $("#principal").children().hide().filter("."+className).show();
}

function showAllCat(){
 $("#principal").children().show();
}

Edit: Fixed the bugs. Tested. It works.

Edit2: Following good suggestion from @gnarf

Upvotes: 1

Related Questions