Dubster
Dubster

Reputation: 21

Select first children in nested list using JavaScript

I am trying to select only the first children under Sally. Using JavaScript, how would I select Car, Boat, & Bike and change the font color to red?

<script type="text/javascript">
$(document).ready(function() {
    var j = jQuery.noConflict();
    j('#content2 ul li ul').children().css('color', '#ff0000');
});
</script>

<div id="content2">
    <div>
        <div>
            <ul>
                <li>Bob</li>
                <li>Sally
                    <ul>
                        <li>Car</li>
                        <li>Boat</li>
                        <li>Bike
                            <ul>
                                <li>Red</li>
                                <li>Green</li>
                                <li>Blue</li>
                            </ul>
                        </li>
                    </ul>
               </li>
               <li>Larry</li>
               <li>Mo</li>
            </ul>
        </div>
    </div>
</div>

Upvotes: 0

Views: 217

Answers (1)

Ry-
Ry-

Reputation: 224983

querySelectorAll will select elements based on a CSS selector, so one way would be:

var elements = document.querySelector('#content2 > div > div > ul > li > ul > li');

Oh, you've got jQuery. Then you just need to be a little more specific, because descendants will be matched by default:

j('#content2 > div > div > ul > li > ul > li').css('color', 'red');

Upvotes: 2

Related Questions