JQuery – Select First, Last, Nth, Second Children

Ever wondering how to select children in JQuery? No? Then skip to the next article.

My case is the following – I present a div with divs, and I try to select its children, changing the borders and the background. Simple as this:

select_children_jq

Thus, first I have given ids as main1, main2 and main 3 to my main divs. Then I have tried to select their children with some properties from within the brackets as “div:last-child” and outside the brackets as last(). Even the works pretty well, adding text “This is the second child”.

Long story short – here comes the code:

<html>
<head>
    <title>VitoshAcademy JQ</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function(){
            $("#main1").last().css({"background": "#888888" , "border-bottom": "3px double red"});
            $("#main1 div:first-child").css({"background": "#CECACE" , "border-bottom": "3px double red"});
           
            $("#main2").children().css({"background": "#999999" , "border-bottom": "3px double red"});
            $("#main2 div:last-child").last().css({"background": "#ABBBBA" , "border-bottom": "3px double blue"});
            
            $("#main3 div:nth-child(2)").append( "<span> - That is the second child!</span>" );
            $("#main3 div:nth-child(3)").css({"border": "5px double green"});
            });
    </script>
</head> 
<body>
    <div id="main1">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>
    <hr />
    <div id="main2">
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div>8</div>
    </div>
    <hr />
    <div id="main3">
        <div>9</div>
        <div>0</div>
        <div>1</div>
        <div>2</div>
    </div>
</body>
</html>

Here is the code in GitHub.

Enjoy it! 😀