Dynamic Text Replacement with JavaScript - Seeing Dynamic Text Replacement in action
(Page 3 of 4 )
As I stated in the section that you just read, to demonstrate how to replace the <h2> headers of the previous sample web page using the dynamic text replacement technique, I’ll define a JavaScript function to traverse the web document tree, find the mentioned headers, and finally substitute them with some basic images.
Having explained how this brand new function will work, here is its signature:
function replaceTextNodes(){
// select all <h2> elements on the web page
var h2=document.getElementsByTagName('h2');
if(!h2){return};
// perform text replacement
for(var i=0;i<h2.length;i++){
// create <img> element
var img=document.createElement('img');
if(h2[i]){
// set <img> attributes
img.setAttribute('src','img'+i+'.gif');
img.setAttribute('width','180px');
img.setAttribute('height','30px');
img.setAttribute('alt',h2[i].firstChild.nodeValue);
// replace text with image
h2[i].replaceChild(img,h2[i].firstChild);
}
}
}
Indeed, the definition of the previous “replaceTextNodes()” JavaScript function is very comprehensive. As you can see this function loops over the complete web page tree, finds its <h2> headers, and then replaces their text nodes with some predefined images. Quite simple, right?
Finally, the previous function should be invoked after the web document has been loaded on the browser, in the following way:
window.onload=function(){
if(document.createElement && document.getElementById &&
document.getElementsByTagName){
replaceTextNodes();
}
}
All right, now that you know how the previous JavaScript function does its thing, let's assume that the images that will replace the text nodes corresponding to the <h2> headers of the sample web page can be created as follows:






In that case, the web page displayed on the browser, after performing the aforementioned text replacement would look like this:

In this case, I used some basic graphics to replace the text nodes included into all the <h2> headers of the previous sample web document, but as you surely know, this can be easily modified, and work with more polished images.
So far, so good. At this point you hopefully grasped the programmatic logic that drives this text replacement approach, which can be quite useful when you need to substitute certain text-based elements of a given web document with some eye-catching graphics. However, if you’re anything like me, then possibly you’ll want to see how the complete text replacement application look, right?
Thus, in the final section of this tutorial, I’ll be listing the full source code of the previous hands-on example. This means that you can use it and eventually incorporate it into your own improvements.
Click on the link below and keep reading, please.
Next: Completing the dynamic text-replacement script >>
More JavaScript Articles
More By Alejandro Gervasio