简体   繁体   中英

jQuery: UL select parent li who have children only

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 have color: red also makes its descendants red, unless there's another style that applies to them.

Adding a style like li { color: black; }li { color: black; } will make it more obvious that your class is indeed only applied to the correct list items.

Your selector is just fine. It's adding the redColor class correctly, but the children inherit the color of their parents, so they turn red as well.

You should override this behaviour by explicitly setting the color of <li> s that don't have the redColor class:

li {
    color:black;
}

See ammended fiddle: http://jsfiddle.net/t6a6G/12/ .

Instead of putting spaces between two things in the CSS, use a ">". So "A > B" means that B is directly a child of A. Also, you were adding the redColor class to everything in the li, and that also includes the ul inside the li. I think you just wanted the strong tags to be red.

$(document).ready(function() {
// Trying to add css class to li who are parents of children
// When working correctly only items 6, 4, and 8 would be red
    $("#test-list > li:has(ul) > strong").addClass("redColor");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM