Houman
Houman

Reputation: 66320

How to select a li with a specific class?

<ul id="attached_deals_tab" class="nav nav-tabs">
  <li class="active">
    <a data-toggle="tab" href="#Test1">Test1</a>
  </li>
  <li class="">
    <a data-toggle="tab" href="#Test2">Test2</a>
  </li>
</ul>

With a jquery like this, I could say get me all list items:

$('#attached_deals_tab li');

But how can I say show me only the li that has class="active" ? In one line please.

I know how to negate it:

$('#attached_deals_tab li:not(.active)');

But not the other way around...

Upvotes: 18

Views: 71513

Answers (5)

kapa
kapa

Reputation: 78681

You should use the child selector to prepare your code for possible future nested lists:

$('#attached_deals_tab > .active')

It will select only direct children. According to the specification, an ul can only have li elements as its children, so when using the child selector, .active should suffice, no need to specify li.active.

By nested lists, I mean something like this:

<ul id="attached_deals_tab">
    <li class="active"></li>
    <li></li>
    <li>
        <ul>
            <li class="active"></li>
            <li></li>
        </ul>
    </li>
</ul>

Reading the documentation on jQuery Selectors will also help a lot.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

You could just use the class once the ul id has been specified:

$("#attached_deals_tab .active");

Unless you have something other than lis in there and that something is also being applied the active class, which would be strange.

Upvotes: 2

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

Simple, do

$('#attached_deals_tab li.active').(...)

Upvotes: 1

codebox
codebox

Reputation: 20254

This should do it, the syntax is just the same as in CSS:

$('#attached_deals_tab li.active');

Upvotes: 5

jholloman
jholloman

Reputation: 1979

$('#attached_deals_tab li.active');

Upvotes: 30

Related Questions