jquery - Error in javascript recursive function -
i have following piece of code (for present case may considered function remove attributes valid html string fed input):
function parse(htmlstr) { console.log(htmlstr); result+="<"+htmlstr.tagname.tolowercase()+">"; var nodes=htmlstr.childnodes; for(i=0;i<nodes.length;i++) { var node=nodes[i]; if(node.nodetype==3) { var text=$.trim(node.nodevalue); if(text!=="") { result+=text; } } else if(node.nodetype==1) { result+=parse(node); } } result+="</"+htmlstr.tagname.tolowercase()+">"; return result; } but not working expected. example, in following case when feed following html input:
<div id="t2"> hi <b> test </b> </div> it returns <div>hi am<div>hi am<b>test</b></div>.
also page crashes if large input given function.
note: know there better implementations of removing attributes string using jquery, need work above function here & complete code not removing attributes, above shortened part of code
there wrong result variable. undefined , global. in each recursion append same string itself, makes crashing huge inputs. (i can't reproduce anything, crashes right away undefined variable error)
btw: argument no htmlstr, domnode. , you're not parsing anything. please don't use wrong self-documenting variable names.
corrected version:
function serialize(domelement) { var tagname = domelement.tagname.tolowercase(); var result = "<"+tagname+">"; // ^^^ ^ not += var children = domelement.childnodes; (var i=0; i<children.length ;i++) { // ^^^ missing if (children[i].nodetype == 3) { result += children[i].data; } else if (children[i].nodetype == 1) { result += serialize(children[i]); // ^^ add child's result here } } result += "</"+tagname+">"; return result; } i not use trim(), produce <div>hi<b>i</b>am</div> <div>hi <b>i</b> am</div>. might .replace(/\s+/g, " ").
Comments
Post a Comment