If you want to add the class depending to the content of the li
you could use :contains
selector :
$( "li:contains('item 2')" ).addClass('X');
Or filter and check text()
content :
$( "li" ).filter(function(){
return $(this).text()==='item 4';
}).addClass('X');
If you want to add class using the index
's use .eq()
like Robiseb's answer show.
EDIT :
I don't know how many <li>
without a link will be in the list. And I don't know what the text inside the <li>
will be.
You could use :
$("li:not(:has(>a))").addClass('X');
Hope this helps.
$("li:not(:has(>a))").addClass('X');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a ...>item 1</a></li>
<li>item 2
<ul>
<li><a ...>item 2-a</a></li>
<li><a ...>item 2-b</a></li>
</ul>
</li>
<li><a ...>item 3</a></li>
<li>item 4
<ul>
<li><a ...>item 4-a</a></li>
<li><a ...>item 4-b</a></li>
</ul>
</li>
<li><a ...>item 5</a></li>
<li><a ...>item 6</a></li>
</ul>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…