简体   繁体   中英

jQuery children method selecting grandchildren

I was following tutorial on net.tuts on jQuery. I am having problem with jQuery children selection method. My understanding with the following function I could change color of the children but it goes more than one level down to change color of all list elements to red. What did I do wrong? I have seen the same script work fine on the video tutorial. Here is the code

<ul class="color_change">
    <li>Item 1</li>
    <li>Item 2</li>
    <li> 
        <ul>
            <li>sub item</li>
            <li>sub item</li>
        </ul>
    </li>
</ul>

<script>
    $('ul.color_change').children('li').css('color','red');
</script>`

You could use that:

DEMO

$('ul.color_change').children('li').not(':has(ul)').css('color','red');

An other way which will set red color for all first level children:

DEMO 2

$('ul.color_change').find('ul').css('color','black').end().children('li').css('color','red');

But better would be to just use CSS rules:

DEMO 3

ul.color_change > li{color:red}
ul.color_change > li > ul{color:black}

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