Cover Image for jQuery contents() method
104 views

jQuery contents() method

The jQuery.contents() method is used to retrieve the child nodes (including text nodes, element nodes, and comment nodes) of each element in the jQuery object. It returns a new jQuery object containing the direct children of each matched element.

Here’s the syntax of the contents() method:

$(selector).contents()

Parameters:

  • selector: The selector expression used to select the elements whose child nodes will be retrieved.

Return Value:
The contents() method returns a new jQuery object containing the child nodes of each matched element.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery contents() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div>
        This is a div.
        <p>This is a paragraph.</p>
        <!-- This is a comment -->
    </div>

    <script>
        $(document).ready(function() {
            // Get the contents of the div element
            var divContents = $("div").contents();

            // Log the contents
            console.log(divContents);
        });
    </script>
</body>
</html>

In this example, we have a <div> element containing text, a <p> element, and a comment. We use the contents() method to retrieve the child nodes of the <div> element.

The output of the above example will be:

Text
<p>This is a paragraph.</p>
<!-- This is a comment -->

In this output, we see that the contents() method has returned a new jQuery object containing the direct child nodes of the <div> element, which includes a text node, the <p> element, and the comment node.

Keep in mind that the contents() method only retrieves the immediate child nodes of the selected elements, not all descendant nodes. If you want to retrieve all descendant nodes (including nested elements), you can use the find() method instead.

The contents() method is useful when you need to work with the direct child nodes of an element and perform specific operations on them. It allows you to access text nodes and comment nodes, which are not directly accessible using other methods like children() or find().

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS