August 20, 2005

Neat little function

I am doing a lot of changing of elements' text within a html document using javascript, I had this little function that would simply replace the text node of an element given, this was fine, until I wanted to add formatting, namely line breaks, our old friend,
.
So I whipped up this little babe, which works a treat:
function changeElementsTextNode(aElement,text) {
if (aElement) {
if (aElement.childNodes) {
for (var i = aElement.childNodes.length-1;i >= 0;i--) {
aElement.removeChild(aElement.childNodes[i]);
}
var textarr = text.split("\n");
for (var i = 0;i < textarr.length;i++) {
var aNode = document.createTextNode(textarr[i]);
aElement.appendChild(aNode);
if (i != textarr.length-1) {
var aNode = document.createElement("br");
aElement.appendChild(aNode);
}
}
}
}
}
just thought I'd share.

- 3 comments by 2 or more people Not publicly viewable

  1. Chris May

    If/When you get to thinking that you might want to add more complex formatting, this looks pretty cool – a javascript implementation of Textile.

    21 Aug 2005, 07:34

  2. thanks, but I've decided no to allow any formatting, It was rarely used and was more trouble than it was worth.

    21 Aug 2005, 23:04

  3. I souped up this little git, to include some formatting, since it was easier to do it in code than with some ugly css fix, plus it means I can use it all over the site.

    01 Sep 2005, 17:29


Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

August 2005

Mo Tu We Th Fr Sa Su
|  Today  | Sep
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31            

Search this blog

Tags

Not signed in
Sign in

Powered by BlogBuilder
© MMXXII