Vineet Kumar
Vineet Kumar

Reputation: 1

Direct child selection in jQuery

$(document).ready(function () {
    $("#one > li").text("fruits");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul>

When I run this javascript on the above HTML then the output changes all the list items to "fruits" including the ones with id="two". Since direct selector (>) should only select the direct child of ul element with id="one" then why is this happening?

Upvotes: 0

Views: 55

Answers (2)

gmast
gmast

Reputation: 192

Actually, the selector you're using is telling "Pick ALL the li that are direct children of element with #one id".

If yout want to change the text of the first item only you can use the ":first-child" pseudo-class.

$("#one > li:first-child").text("My Text");

Take a look to this page for more info on css pseudo-classes.

Upvotes: -2

j08691
j08691

Reputation: 207943

You're telling jQuery to change the content of all child list items to "fruits", so it wipes out the nested list and does just that. If you want to skip list items that contains other lists, then you need to tell it that:

$(document).ready(function () {
    $("#one > li:not(:has('ul'))").text("fruits");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul>

Upvotes: 5

Related Questions