Results 1 to 3 of 3

Thread: [RESOLVED] Process HTML as text and add to node

  1. #1

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Resolved [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;
    	}

  2. #2
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    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.

  3. #3

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    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
  •  



Click Here to Expand Forum to Full Width