07/01/2019, 14:16

JQuery API: :first-child Selector

First-child Selector sẽ lựa chọn phần tử con đầu tiên của phần tử cha nào đó. Trong khi :first chỉ có thể trả tìm kiếm duy nhất một phần tử, :first-child selector có thể tìm kiếm phần tử con đầu tiên cho nhiều phần tử cha(xem ví dụ để hiểu rõ hơn). ...

First-child Selector sẽ lựa chọn phần tử con đầu tiên của phần tử cha nào đó.

Trong khi :first chỉ có thể trả tìm kiếm duy nhất một phần tử, :first-child selector có thể tìm kiếm phần tử con đầu tiên cho nhiều phần tử cha(xem ví dụ để hiểu rõ hơn).

Cú pháp

Cú pháp
jQuery( ":first-child" )

Ví dụ

Tìm kiếm thẻ span đầu tiên của các thẻ div và đổi màu cho chúng:

Code RUN
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Học lập trình miễn phí tại code24h.com</title>
        <script src="https://code24h.com/cnd/js/jquery/jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <h1>Học lập trình miễn phí tại code24h.com</h1>
    
        <div>
            <span>PHP</span>
            <span>Css</span>
            <span>HTML</span>
        </div>
        <div>
            <span>Glen,</span>
            <span>Tane,</span>
            <span>Ralph</span>
        </div>
        <button onclick="myFunction()">Click vào đây để xem kết quả</button>
        <script>
            function myFunction(){
                $( "div span:first-child" ).css( "color", "red");
            }
        </script>
    </body>
</html>

Kết quả:

Tham khảo: jquery.com

Nguồn: code24h.com

0