Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

jQuery: Make $(this) apply ONLY to the last child clicked

How can I get $(this) to ONLY apply to the last child clicked on?  For example, if I click on "Kale" only Kale should become red and not all parent <li> tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Examples</title>
<style type="text/css">
li {
cursor: pointer;
}

</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
 $('li').click(function (e) {
        $('li').css('background','transparent');
        $(this).css('background','red');
 });
});

</script>

</head>
<body>

<ul>
    <li>Animals
     <ul>
       <li>Mammals</li>
       <li>Reptiles</li>
       <li>Fish</li>
     </ul>
    </li>
    <li>Minerals
     <ul>
       <li>Salt</li>
     </ul>
    </li>
    <li>Vegitation
        <ul>
            <li>Fruit
                <ul>
                    <li>Apple</li>
                    <li>Peach</li>
                    <li>Pear</li>
                </ul>
            </li>
            <li>Vegies
                <ul>
                    <li>Leafy
                         <ul>
                             <li>Kale</li>
                             <li>Spinich</li>
                             <li>Lettuce</li>
                        </ul>
                    </li>
                    <li>Roots
                         <ul>
                             <li>Kale</li>
                             <li>Spinich</li>
                             <li>Lettuce</li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>


</body>
</html>

Open in new window

Avatar of Scott Fell
Scott Fell
Flag of United States of America image

$(document).ready(function () {
 $('li li').click(function (e) {
        $('li').css('background','transparent');
        $(this).css('background','red');
 });
});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial