How do I select text nodes with jQuery?

jQuery provides several methods to select and manipulate text nodes within the DOM. Text nodes are the actual text content inside HTML elements, separate from the element tags themselves.

Using the contents() Method

The most effective way to select text nodes in jQuery is using the contents() method combined with a filter. The contents() method returns all direct children of selected elements, including text nodes.

Example

Here's how to select and manipulate text nodes ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div id="container">
        This is a text node
        <span>This is inside a span</span>
        Another text node here
    </div>
    
    <script>
        // Select all text nodes within the container
        $('#container').contents().filter(function() {
            return this.nodeType === 3; // 3 represents text nodes
        }).wrap('<em></em>');
    </script>
</body>
</html>

Filtering Text Nodes

You can also filter text nodes based on their content or apply specific operations ?

// Select non-empty text nodes
$('#container').contents().filter(function() {
    return this.nodeType === 3 && $.trim(this.nodeValue).length > 0;
});

// Replace text in text nodes
$('#container').contents().filter(function() {
    return this.nodeType === 3;
}).each(function() {
    this.nodeValue = this.nodeValue.replace('old', 'new');
});

Node Types Reference

Understanding DOM node types is crucial when working with text nodes ?

  • nodeType 1 ? Element nodes (HTML tags)
  • nodeType 3 ? Text nodes (actual text content)
  • nodeType 8 ? Comment nodes

Conclusion

Selecting text nodes in jQuery requires using the contents() method combined with filtering by nodeType === 3. This approach allows you to directly manipulate the text content separate from HTML elements.

Updated on: 2026-03-13T18:48:49+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements