Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select li from ul having only one class in jquery

Tags:

jquery

I want to select all li elements from ul having class "one" only

<ul class="one">
<li class="heading">
<li class="list">
<li class="list">
<li class="list">
<li class="list">
</ul>       
<ul class="one two ">
<li class="heading">
<li class="list">
<li class="list">
<li class="list">
<li class="list">
</ul>                        
like image 681
Abhishek Avatar asked Feb 02 '12 12:02

Abhishek


People also ask

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How can I select an element with multiple classes in jQuery?

In jQuery, we can select elements with multiple classes using the . class selector.


2 Answers

Easiest:

$('ul[class="one"] li');

Alternative, select .one but not .two:

$('ul.one:not(.two) li');
like image 161
Andy E Avatar answered Sep 24 '22 19:09

Andy E


You can use the jquery filter function to get a count of how many classes have been assigned to the element. When looking for all UL's with class 'one' only then the number of unique classes against the item will be 1. Once you have the filtered UL's you can simply select the sub LI's.

var listItems = 
$('ul.one')
.filter(function(index) {
  return $(this).attr('class').split(' ').length == 1;
})
.find('li');
like image 25
Brian Scott Avatar answered Sep 23 '22 19:09

Brian Scott