How to select text nodes using jQuery ?

Text nodes are a type of node that denotes the actual text inside an element. The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property.

The required element is first selected using the jQuery selector. The contents() method is used on selected elements. This method is used to return the direct children of an element including all the text and comment nodes.

The filter() method is used on these returned elements to filter only the text nodes required. The custom filter function checks if the nodeType property of the nodes return equal to the Node.TEXT_NODE value.



The “Node.TEXT_NODE” value is used to identify a text node from other nodes. Alternatively, the integer value “3” could also be used to identify a text node. The filter() method will now only return the nodes that are textNodes. Therefore this method can be used to select the textNodes of any element.

Syntax:

filter_none

edit
close

play_arrow

link
brightness_4
code

selectedElement = $("elementRequired").contents();
 
textNodes = selectedElement.filter(function () {
  return this.nodeType === Node.TEXT_NODE;
});

chevron_right


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to select text nodes using jQuery?
    </title>
      
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to select text nodes using jQuery?
    </b>
      
    <p class="example">
        This is line 1<br>
        This is line 2<br>
        This is line 3
    </p>
      
    <button onclick="getTextNodes()">
        Click to get Text Nodes
    </button>
      
    <script type="text/javascript">
        function getTextNodes() {
            selectedElement = $(".example").contents();
          
            textNodes = selectedElement.filter(function ()
            {
                return this.nodeType === Node.TEXT_NODE;
            });
              
            console.log(textNodes);
        }
    </script>
</body>
  
</html>

chevron_right


Output:

  • Display:
    textnodes-display
  • Console:
    textnodes-console


My Personal Notes arrow_drop_up

Maybe this silence is dangerous

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.