jquery
  1. jquery-contents

JQuery contents()

The contents() method is a jQuery method that returns all the child nodes of the selected HTML element, including both text and HTML elements.

Syntax

The content() method has the following syntax:

$(selector).contents()

Use

The contents() method is useful when you want to retrieve all the child nodes of an HTML element, including text nodes and HTML element nodes, and perform some manipulation on them.

Unlike the children() method, the contents() method returns not only the direct children of the selected element, but all the descendants of the element, including nested HTML elements.

Example

Here is an example of using the contents() method to retrieve all the child nodes of a selected element:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

  <div id="mydiv">
    <p>Some text <strong>with strong emphasis</strong></p>
  </div>

  <script>
    $(document).ready(function(){
        var childNodes = $("#mydiv").contents();

        // Output the types of child nodes for demonstration purposes
        childNodes.each(function(index, node) {
          console.log("Type: " + node.nodeType + ", Node: " + node.nodeName);
        });
    });
  </script>

</body>
</html>
Try Playground

In this example, the contents() method is applied to the mydiv element, which contains a p element with some text and a nested strong element. The contents() method returns all the child nodes of the mydiv element, including the p element, the text node, and the strong element.

Summary

The contents() method is a jQuery method that can be used to retrieve all the child nodes of a selected element, including both text nodes and HTML element nodes. This method can be useful if you need to manipulate the child nodes of selected element or perform some other operation on them. Because contents() returns all descendants rather than only direct children, it is a more inclusive method than children().

Published on: