jQuery contents() Method



The contents() method in jQuery is used to retrieve the child nodes, including text and comment nodes, of each element in the set of matched elements.

Unlike the children() method, contents() includes text nodes and comment nodes.

Syntax

Following is the syntax of contents() method in jQuery −

$(selector).contents()

Parameters

This method does not accept any parameters.

Example

In the following example, we are using the contents() method to select all the text nodes inside the <div> element and wrap them with a span element of background color yellow −

<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>

After clicking the button, the content inside the <div> element will be wraped with a span element of yellow background color.

jquery_ref_traversing.htm
Advertisements