Tim
Tim

Reputation: 3

using hasClass() to display matching list items

Question from JavaScript newbie. I have a list like this:

<ul>
<li class="class1 class2"> </li>
<li class="class3 class4"> </li>
<li class="class1 class3"> </li>
</ul>

All list items are initially hidden, and I need to check if an item has a certain class to show it. And if several items contain one class, I need to show them all. The problem is, I don't know how to target the elements correctly:

if ($('li').hasClass('class3')) {
/* show this li */
}

What should I write here?

Upvotes: 0

Views: 775

Answers (5)

demiron
demiron

Reputation: 1

I think you could add it, and remove it from the siblings: This is the best way.

$("li").on("click", function(){
  $(this)
    .addClass("className")
    .siblings()
      .removeClass("className");
});

Upvotes: 0

genesis
genesis

Reputation: 50966

$('li').each(function() {
    if ($(this).hasClass('class3')){
       //Do stuff
    }
}).show()

Upvotes: 1

Eric
Eric

Reputation: 97565

That won't work, as hasClass only checks the first li returns whether any of the lis have the class. Just do this:

$('li.class3').show()

Another way of writing it, if your conditions get more complex, is:

$('li').filter(function() {
    return $(this).hasClass('class3');
}).show()

Upvotes: 8

Naga Harish M
Naga Harish M

Reputation: 2789

try like this

$('li.class3').css('display','block');
if($('li.class3').size()>3)
{
$('li').css('display','block');
}

Upvotes: 0

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

$("ul li").each(function() {
    if ($(this).hasClass('class3')) {
        //do what you need, 'this' is your li
    }
});

Upvotes: 1

Related Questions