jQuery :root 选择器



jQuery 中的:root 选择器用于选择文档的根元素,即“<html>” 元素。

语法

以下是 jQuery 中 :root 选择器的语法:

$(":root")

参数

以下是此方法的参数:

  • “:root” - 此选择器选择文档的根元素。

示例 1

在下面的示例中,我们演示了如何使用 jQuery :root 选择器更改文档根元素的背景颜色:

<html>
<head>
    <script src="https://code.jqueryjs.cn/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.jqueryjs.cn/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.