jQuery :root 選擇器



jQuery 中的:root 選擇器用於選擇文件的根元素,即“<html>” 元素。

語法

以下是 jQuery 中 :root 選擇器的語法:

$(":root")

引數

以下是此方法的引數:

  • “:root” - 此選擇器選擇文件的根元素。

示例 1

在下面的示例中,我們演示瞭如何使用 jQuery :root 選擇器更改文件根元素的背景顏色:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $(":root").css("background-color", "lightblue");
        });
    </script>
</head>
<body>
    <p>This example changes the background color of the root element.</p>
</body>
</html>

執行上述程式後,文件的根元素 (<html>) 將以淺藍色背景顏色突出顯示。

示例 2

在此示例中,我們演示瞭如何使用 jQuery :root 選擇器向根元素內的所有元素新增邊框:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $(":root *").css("border", "1px solid red");
        });
    </script>
</head>
<body>
    <p>This example adds a border to all elements within the root.</p>
    <div>
        <p>Nested paragraph inside a div.</p>
    </div>
</body>
</html>

執行上述程式後,根元素內的所有元素都將以實線紅色邊框突出顯示。

jquery_ref_selectors.htm
廣告
© . All rights reserved.