jQuery contents() 方法



jQuery 中的 contents() 方法用於檢索匹配元素集中每個元素的子節點,包括文字節點和註釋節點。

與 children() 方法不同,contents() 包括文字節點和註釋節點。

語法

以下是 jQuery 中 contents() 方法的語法:

$(selector).contents()

引數

此方法不接受任何引數。

示例

在以下示例中,我們使用 contents() 方法選擇 <div> 元素內部的所有文字節點,並用背景顏色為黃色的 span 元素將其包裹:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").contents().filter(function() {
                    return this.nodeType === 3; // Filter for text nodes
                }).wrap("<span style='background-color: yellow;'/>");
            });
        });
    </script>
</head>
<body>

<div>Hello world! This is a beautiful day!</div>
<br>
<button>Click me</button><br>
</body>
</html>

單擊按鈕後,<div> 元素內部的內容將用背景顏色為黃色的 span 元素包裹。

jquery_ref_traversing.htm
廣告