This has been boggling my mind all afternoon, how do I get my jQuery statement below to only select parent <li> who have children?
To put it simply, I need to add a css class to <li> items 6, 4 & 8 because they have children directly below them. My statement goes too deep, it adds the redColor class to li’s 7, 10, 9, 11, 12..
$(document).ready(function () {
$("#test-list li:has(ul)").addClass("redColor");
});
<ul id="test-list">
<li id="listItem_1"> <strong>Item 1</strong> </li>
<li id="listItem_2"> <strong>Item 2</strong> </li>
<li id="listItem_3"> <strong>Item 3</strong> </li>
<li id="listItem_5"> <strong>Item 5</strong> </li>
<li id="listItem_6"> <strong>Item 6</strong>
<ul>
<li id="listItem_4"> <strong>Item 4</strong>
<ul>
<li id="listItem_7"> <strong>Item 7</strong> </li>
<li id="listItem_10"> <strong>Item 10</strong> </li>
</ul>
</li>
</ul>
</li>
<li id="listItem_8"> <strong>Item 8</strong>
<ul>
<li id="listItem_9"> <strong>Item 9</strong> </li>
<li id="listItem_11"> <strong>Item 11</strong> </li>
<li id="listItem_12"> <strong>Item 12</strong> </li>
</ul>
</li>
</ul>
View on jfiddle as well: http://jsfiddle.net/t6a6G/9/
Thank you in advance!
If you look closely, you’ll see that your jQuery selector is actually working correctly, and only li’s 6, 4, and 8 have the class you’re adding.
The reason the other li’s are turning red is that the default color is
inherit, the same color as your parent. So setting an li to havecolor: redalso makes its descendants red, unless there’s another style that applies to them.Adding a style like
li { color: black; }will make it more obvious that your class is indeed only applied to the correct list items.