Lukas Lukas - 5 months ago 12
jQuery Question

Create filter for li in table using jquery

I'm not so familiar with javascript and for most of you it will be very easy but...

I'd like to create filter for my li> tag. Found this code on the internet which is basically the same but using div> and I'm unable to modify that to use it on li>

Here's my code.

<button class="active button" id="all">Show All</button>
<button class="button" id="a">Show A</button>
<button class="button" id="b">Show B</button>
<button class="button" id="c">Show C</button>
<button class="button" id="d">Show D</button>

<div id="parent">
<ul class="rig columns-3">
<li class="a">
<img src="image_1.jpg" />
</li>
<li class="b">
<img src="image_1.jpg" />
</li>
</ul>
</div>


And the script I'm using:

var $btns = $('.button').click(function() {
if (this.id == 'all') {
$('#parent > li').fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > li').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})


Could anyone help me please? I'd very appriciate that :-)

Answer

{element a} > {element b} is a selector for a direct child. This means in that case #parent > li will target <li> tags just after the tag with id parent and not thoses inside another tag like this

<div id="parent">
    <li>
    <--!This will be selected>
    <li>
    <div class="child">
        <li>
        <--!This will not be selected>
        </li>    
    </div>
</div>

In your case, you could use#parent > ul > li or just #parent li this doesn't needs li to be a first child of tag with id parent

In that case your script would look like this

var $btns = $('.button').click(function() {
  if (this.id == 'all') {
    $('#parent > ul > li').fadeIn(450);
  } else {
    var $el = $('.' + this.id).fadeIn(450);
    $('#parent > ul> li').not($el).hide();
  }
  $btns.removeClass('active');
  $(this).addClass('active');
}) 
Comments