Ok, the person I wrote this code for asked if there was a way to split the varios words up which are contained in one node type
#text (
node type 3)... So I reworked the code to include the DOM
splitText() method...
CODE
<script type="text/javascript">
<!--//
function addSpans(){ // written by: WillyDuitt@hotmail.com //;
var p = document.getElementsByTagName('p');
for(var i=0; i<p.length; i++){
for(var j=p[i].childNodes.length-1; j>-1; j--){
var node=p[i].childNodes[j];
if(node.nodeType == 1){
for(var k=0; k<node.childNodes.length; k++){
var span = document.createElement('span');
span.style.cursor = 'pointer';
span.className = node.className;
span.style.color = 'red'; // TESTING PURPOSES ONLY, PLEASE REMOVE //;
span.onclick = function(){ alert(this.innerHTML+':className='+this.className) };
span.appendChild(document.createTextNode(node.childNodes[k].nodeValue));
node.childNodes[k].parentNode.replaceChild(span,node.childNodes[k]);
}
}
if(node.nodeType == 3){
while(node.nodeValue.lastIndexOf(' ')>-1){
var span = document.createElement('span');
span.style.cursor = 'pointer';
span.style.color = 'blue'; // TESTING PURPOSES ONLY, PLEASE REMOVE //;
span.onclick = function(){ alert(this.innerHTML+': This word has no class!') };
span.appendChild(node.splitText(node.nodeValue.lastIndexOf(' ')));
p[i].insertBefore(span,node.nextSibling);
}
}
}
var span = document.createElement('span');
span.style.cursor = 'pointer';
span.style.color = 'blue'; // TESTING PURPOSES ONLY, PLEASE REMOVE //;
span.onclick = function(){ alert(this.innerHTML+': This word has no class!') };
span.appendChild(document.createTextNode(node.nodeValue));
node.parentNode.replaceChild(span,node);
}
} window.###### = addSpans;
//-->
</script>
</head>
<body>
<div>
<p>The test <span class="noun">Hare</span> <span class="verb">ran</span> past the <span class="adj">lazy</span> <span class="noun">Tortoise</span>.</p>
<p>The <span class="noun">Hare</span> <span class="verb">ran</span> past the <span class="adj">lazy</span> <span class="noun">Tortoise</span> test.</p>
</div>
.....Willy
Edit: Fixed a minor oversight of using params when I should have used square bracket notation: var node=p[i].childNodes[j]; ... This was preventing the script to work properly in Mozzila based browsers, which I neglected to test because I only assumed I was writing cross-browser compatable code... Alls well now and the script has now been tested in: IE, Firefox, Opera, Mozilla....