jQuery 父子選擇器



jQuery 中的父子選擇器用於選擇指定父元素的所有子孫元素。

子孫元素:巢狀在另一個元素內的元素。它包括該元素的子元素、孫元素、曾孫元素等。

語法

以下是 jQuery 父子選擇器的語法:

("parent descendant")

引數

以下是上述語法的描述:

  • 父元素: 指定父元素。
  • 子孫元素: 指定要選擇的子孫元素。

示例 1

在下面的例子中,我們使用“jQuery 父子選擇器”來選擇所有作為<div>子孫元素的<span>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("div span").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>
        <p>This is a paragraph with a <span>span element</span> inside a div.</p>
        <div>
            This is a nested div with another <span>span element</span>.
        </div>
    </div>
    <p>This is a paragraph with a <span>span element</span> outside the div.</p>
</body>
</html>

執行上述程式後,所有作為<div>子孫元素的<span>元素的背景顏色將變為黃色。

示例 2

在這個例子中,我們選擇所有作為<section>子孫元素的<p>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("section p").hide();
        });
    </script>
</head>
<body>
    <section>
        <h1>Section Header</h1>
        <p>This is a paragraph inside a section.</p>
        <div>
            <p>This is a nested paragraph inside a div within a section.</p>
        </div>
    </section>
    <p>This is a paragraph outside the section.</p>
</body>
</html>

執行後,所有作為<section>子孫元素的<p>元素將被隱藏。

示例 3

在這裡,我們選擇所有作為<ul>子孫元素的<li>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all <li> elements that are descendants of <ul>
            $("ul li").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>List item 1</li>
        <li>List item 2
            <ul>
                <li>Nested list item 1</li>
                <li>Nested list item 2</li>
            </ul>
        </li>
    </ul>
</body>
</html>

執行後,所有作為<ul>子孫元素的<li>元素的背景顏色將變為黃色。

jquery_ref_selectors.htm
廣告