How to select a li with a specific class?
-
04-07-2021 - |
Domanda
<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...
Soluzione
$('#attached_deals_tab li.active');
Altri suggerimenti
This should do it, the syntax is just the same as in CSS:
$('#attached_deals_tab li.active');
You could just use the class once the ul
id has been specified:
$("#attached_deals_tab .active");
Unless you have something other than li
s in there and that something is also being applied the active
class, which would be strange.
Simple, do
$('#attached_deals_tab li.active').(...)
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.