Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
