user2294256
user2294256

Reputation: 1049

issue with 'first-child' selector in jquery

<html>
<head>
<style type="text/css">
    .hori {
    color:red;
    }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
        $('#car :first-child').addClass('hori');
});
</script>
</head>
<body>
    <ul id="car">
        <li>Honda
            <ul>
                <li>Jazz</li>
                <li>Freed</li>
                <li>CRV</li>
                <li>Oddesey</li>
            </ul>
        </li>
        <li>Nissan
            <ul>
                <li>Grand Livina</li>
                <li>Livina X-gear</li>
                <li>X-Trail</li>
            </ul>
        </li>       
        <li>Toyota
            <ul>
                <li>Fortuner</li>
                <li>Prius</li>
                <li>Innova</li>
            </ul>       
        </li>       
    </ul>
</body>
</html>

Question:

I want to put class:hori(make red color) to this list:

        <li>Honda
            <ul>
                <li>Jazz</li>
                <li>Freed</li>
                <li>CRV</li>
                <li>Oddesey</li>
            </ul>
        </li>

So I use $('#car :first-child').addClass('hori');But the output is not what I want. Except Nissan and Toyota, all the texts turns into red color. so what is wrong with the css selector code?

Upvotes: 0

Views: 143

Answers (2)

sakhunzai
sakhunzai

Reputation: 14470

You need to tell which first child exactly, please see the jsfiddle , I have changed the html little bit

html

<ul id="car">
    <li><span>Honda</span>
            <ul>
                <li>Jazz</li>
                <li>Freed</li>
                <li>CRV</li>
                <li>Oddesey</li>
            </ul>
        </li>
    <li><span>Nissan</span>
            <ul>
                <li>Grand Livina</li>
                <li>Livina X-gear</li>
                <li>X-Trail</li>
            </ul>
        </li>       
    <li><span>Toyota</span>
            <ul>
                <li>Fortuner</li>
                <li>Prius</li>
                <li>Innova</li>
            </ul>       
        </li>       
    </ul>

css

.hori { color:red;}
.tori {color:green;}
.lori {color:blue;}

js

$(document).ready(function() {
       $('#car li>:first-child').addClass('lori');
        $('#car >:first-child').addClass('hori');
        $('#car li > ul > li:first-child').addClass('tori');
});

Upvotes: 0

No Results Found
No Results Found

Reputation: 102735

#car :first-child selects every element that is a first child of anything within the #car element.

To select only the first <li> use this instead:

$('#car > :first-child').addClass('hori');

The > will make sure only to select a direct descendant of #car.

Of course, you don't really need jQuery as this can be done in CSS as well.

Upvotes: 3

Related Questions