Target :nth-child

by kaikemono

HTML

Click The List...
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>

CSS

body {
    font-family: "Helvetica Neue";
    font-weight: 300;
}

ul {
    border: 1px solid rgba(000,000,000,0.25);
    cursor: pointer;
    margin-top: 1em;
    padding: 10px;
}

li {
    margin-bottom: 5px;
}

.a {
    background-color: #d3e5af;
}

.b {
    background-color: #deb7d2;
}

JavaScript

$('ul').click(function() {

    // "this" refers to the <ul> element in this example
    // use eq2 to target the 3rd child (zero-based index)
    $(this).children(':eq(2)').toggleClass('a');

    //use nth-child(5) to target the 5th child
    $(this).children(':nth-child(5)').toggleClass('b');

});