|
-
Feb 2nd, 2010, 01:26 PM
#1
Thread Starter
Stack Overflow moderator
[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;
}
-
Feb 2nd, 2010, 02:21 PM
#2
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));
}
Last edited by SambaNeko; Feb 2nd, 2010 at 02:34 PM.
-
Feb 2nd, 2010, 03:20 PM
#3
Thread Starter
Stack Overflow moderator
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!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|