[RESOLVED] Process HTML as text and add to node
I have this JavaScript code to turn HTML into nodes, but when I call it with "<b>The</b> HTML <i>was</i> changed.", I get "The HTML was". I've looked over it and I can't see what's wrong. There are no errors reported.
Code:
function getHtml(el,n) {
var nestinglevel = 0;
var els = new Array();
var cur = "";
for(var i = 0;i<n.length;i++) {
if(n.charAt(i) != "<") {
cur += n.charAt(i);
} else {
if(nestinglevel==0) {
el.appendChild(document.createTextNode(cur));
} else {
els[nestinglevel-1].appendChild(document.createTextNode(cur));
}
cur = "";
if(n.charAt(i+1) == "/") {
nestinglevel--;
if(nestinglevel==0) {
el.appendChild(els[0]);
} else {
els[nestinglevel-1].appendChild(els[nestinglevel]);
}
while(n.charAt(i) != ">") i++;
} else {
//read the node type.
var ntype = "";
i++;
while(n.charAt(i) != ">") {
ntype += n.charAt(i);
i++;
}
var n_node = document.createElement(ntype);
els[nestinglevel++] = n_node;
}
}
}
return false;
}
Re: Process HTML as text and add to node
This seem overly complicated for what I imagine you're trying to do, but I could be wrong, so please also show how you are using this function.
If any case, your function appears to work on the logic of "collect text on this loop, then append to element on the next loop." So when you get to the end, you're not getting to the appending. You could add this right before the end of your for() loop:
Code:
if(i == n.length-1){
el.appendChild(document.createTextNode(cur));
}
Re: Process HTML as text and add to node
Oh, that's right! I'm only appending a new text node when there's a "<". Thanks, resolved!