user2714421 user2714421 - 1 month ago 5
Javascript Question

Select an element with jquery in a nested list

I have the following HTML

<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>


I want to add a class to 'item 2' and 'item 4' with jquery using
.has
but can't find a way.

Answer

Only selecting for list items without anchors, as clarified in the questions comments.

var parentList = $('ul'); // something more specific is assumed.
parentList.children('li').children().not('a').parent().addClass('some-class');

Using "contains" makes the solution dependent on content, not structure. Using "eq" or similar "nth"-like functionality is assuming that the given example is the only structure, whereas I think it is planned as generated code that may extend to a much longer length, but will always keep the structure defined in the snippet.

Comments