user2714421 user2714421 - 1 year ago 74
Javascript Question

Select an element with jquery in a nested list

I have the following HTML

<li><a ...>item 1</a></li>
<li>item 2
<li><a ...>item 2-a</a></li>
<li><a ...>item 2-b</a></li>
<li><a ...>item 3</a></li>
<li>item 4
<li><a ...>item 4-a</a></li>
<li><a ...>item 4-b</a></li>
<li><a ...>item 5</a></li>
<li><a ...>item 6</a></li>

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

Answer Source

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

var parentList = $('ul'); // something more specific is assumed.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download