Replacing Text Nodes With jQuery
This morning on Twitter, I came across a Tweet from Robert Rawlins (aka. @SirRawlins) asking about replacing text values within a DOM element. He had a situation in which a node contained mixed children; that is, the node contained both element nodes (type 1) and text nodes (type 3). What he wanted to do was replace one of the text nodes, leaving the element nodes unaltered. While we primarily deal with element nodes, jQuery is certainly equipped to deal with text nodes when necessary.
NOTE: Rob Rawlins already solved this problem by the time I finished writing this; but, I figured I would post it for reference.
Typically, when we think about gathering the children of a DOM node using jQuery, we think about the children() method. This collects all of the elements that are the direct descendants of the given node. In most cases, this is what we want - the Element nodes. In rare cases, however, we do want to get at the Text nodes contained within an element. To do this, we can use the contents() method. The contents() method, like the children() method, gathers up directly descendant nodes; however, unlike the children() method, the contents() method includes both Element and Text nodes within its aggregate.
Once we can include text nodes in our jQuery collections, we can start to replace them as we would replace any other DOM node we have a reference to. To see this in action, take a look at the following code:
<!DOCTYPE html>
<html>
<head>
<title>Replacing Text Nodes With jQuery</title>
<script type="text/javascript" src="./jquery-1.6.1.js"></script>
</head>
<body>
<h1>
Replacing Text Nodes With jQuery
</h1>
<p class="statement">
Helena Bonham Carter is <em>hella</em> cool.
</p>
<!--
Now that the DOM has *mostly* loaded, let's replace out
some of the TEXT data with new TEXT data using jQuery.
-->
<script type="text/javascript">
// I return true if the current context (node) is a text node
// in an HTML DOM.
//
// NOTE: This will be used as a filter() argument.
function isTextNode(){
// If this is a text node, return true.
return( this.nodeType === 3 );
}
// Get the text nodes in our statement paragraph. Contents()
// will get us ALL children, including non-element nodes.
// Then, we can filter those down to the final text one.
var textNodes = $( "p.statement" ).contents()
.filter( isTextNode )
;
// Now, let's only look at the LAST text node ("cool.").
var lastTextNode = textNodes.last();
// Replace the last text node with a new text node.
//
// NOTE: I could have just passed a simple string into the
// replaceWith() function; however, I chose to go with a
// createTextNode() in order to make sure that jQuery didn't
// misinterpret the value that was being passed-in.
lastTextNode.replaceWith(
document.createTextNode( " sexy!!!" )
);
</script>
</body>
</html>
Here, we have a paragraph that contains mixed children - both element and text nodes. When the DOM has loaded, we are getting a reference to the last text node within the paragraph and replacing it with a new text node. And, when we run the above code, we get the following output:
Helena Bonham Carter is hella sexy!!!
Notice that the "cool." was replaced with "sexy!!!". Also, notice that my replacement text takes into account that the last text node includes both leading and trailing white space. As such, the replacement text also has to include leading and (optionally) trailing white space so as not to have the resultant text insertion butt-up against the previous element.
Most of the time, jQuery allows us to work very efficiently with Element nodes contained within the DOM. However, at times, we need to access non-Element nodes; we need to access the raw Text nodes of the DOM tree. In such cases, we can still use jQuery to make our lives easier.
Want to use code from this post? Check out the license.
Reader Comments
Ah, good man!
Good job on writing this up, thank you!
It's great when you get introduced to new approaches of traversing through the DOM like this, opens up so many other lines of thought, breaking age-old habits of using methods like children() all the time.
Cheers again bud.
Robert
Excellent writeup Ben. We often forget that there are other things besides simple elements to work with.
Great article dude!
One thing i am always missing, when reading one of your posts including sourcecodes is a better syntax-highlighter. Its a bit more difficult than it has to be.
Cheers
@Robert,
Hey man, thanks for the inspiration :)
@Richard,
Using elements just makes things so easy. If I recall correctly from Rob's tweets, he was dealing with content that he was not actually authoring (as such, he had to deal with the text nodes). Probably, if you could go back and do it from scratch, it'd be easier to just throw a SPAN in there somewhere for easy reference. Elements are just easier to do anything with.
@Philipp,
Yeah, WORD UP to that! My color coder basically only works for ColdFusion. When it hits JavaScript, it has no idea what to do. I really gotta work on this.
Part of the problem is that I can't use the typically syntax highlighters because my code is stored in Unordered Lists which makes dealing with them a bit more difficult (but gives me greater control over the layout and flow).
I'll put some time in to updating this. Especially now that I am working with JavaScript so much more than I used to.
Thanks for your nice piece of code.
Keep up the good work!
Thank you so much for this! I spent all evening trying to figure this out and I'm not that handy with JS (which is why I use jQuery). This article came to the rescue and saved me many hours of stress!
Thanks! Excactly what I've searched for.