PDA

View Full Version : replace a peace of text?



lankinator
05-28-2007, 03:09 PM
i have a huch at how this might be possible (innerHTML tag) but basically i would like a bit of help in making a script that:

Will get a div by id
Will look through that div and find a certain peace of text
will replace that peace of text with a peace of html (eg: <span id="">test</span>)


all help much appreciated :)

Twey
05-28-2007, 03:45 PM
Sure you don't want to replace it with a war of text?

innerHTML is indeed the easiest way, but not the best. Try:
function surroundText(inEl, text, withEl) {
var nv;
for(var i = 0, e = inEl.childNodes; i < e.length; ++i)
if(e[i].nodeType === 3) {
if((nv = e[i].nodeValue).indexOf(text) !== -1) {
var tels = [
nv.substr(nv.indexOf(text) + text.length),
text,
nv.substr(0, nv.indexOf(text))
];
for(var j = 0; j < tels.length; ++j)
inEl.insertBefore(e[i], document.createTextNode(tels[j]));
inEl.parentNode.removeChild(inEl);
return true;
}
} else
if(surroundText(e[i], text, withEl))
return true;
return false;
}Untested.