jQuery 父元素 > 子元素 選擇器



jQuery 中的 **父元素 > 子元素 選擇器** 用於選擇巢狀在父元素內的直接子元素。

語法

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

("parent > child")

引數

以下是上述語法的描述:

  • **父元素:** 指定父元素。
  • **子元素:** 指定父元素內的直接子元素。

示例 1

在下面的示例中,我們使用 “jQuery 父元素 > 子元素 選擇器” 來選擇 <div> 元素的直接子段落:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        div {
            padding: 10px;
            border: 1px solid black;
        }
        p {
            margin: 5px;
            padding: 5px;
            border: 1px solid blue;
        }
    </style>
    <script>
        $(document).ready(function(){
            // Select and apply styles to direct child paragraphs of div
            $("div > p").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>
        <p>First paragraph (direct child)</p>
        <span><p>Child paragraph within span (not direct child)</p></span>
        <p>Second paragraph (direct child)</p>
    </div>
</body>
</html>

執行上述程式後,<div> 元素的直接子段落將以黃色背景顏色突出顯示。

示例 2

在這個示例中,我們選擇 <ul> 的直接子列表項:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        ul {
            padding: 10px;
            border: 1px solid black;
        }
        li {
            margin: 5px;
            padding: 5px;
            border: 1px solid green;
        }
    </style>
    <script>
        $(document).ready(function(){
            // Select and apply styles to direct child list items of ul
            $("ul > li").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>First item (direct child)</li>
        <li>Second item (direct child)</li>
    </ul>
</body>
</html>

執行後,<div> 元素的直接子列表項將以黃色背景顏色突出顯示。

jquery_ref_selectors.htm
廣告