I have the following piece of code (for the present case it may be considered as a function to remove the attributes from a valid html string fed as 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 it is not working as expected. For example, in the following case when I feed it the following html as input:
<div id="t2">
Hi I am
<b>
Test
</b>
</div>
it returns <div>Hi I am<div>Hi I am<b>Test</b></div>.
Also the page crashes if some large input is given to the function.
NOTE: I know there are better implementations of removing attributes from a string using jQuery, but I need to work with the above function here & also the complete code is not for removing attributes, the above is just a shortened part of the code
There is something wrong with your
resultvariable. It is undefined and global. In each recursion you would append the same string to itself, which also makes it crashing for huge inputs. (I can’t reproduce anything, it crashes right away with aUndefined variableError)BTW: Your argument is no
htmlStr, it is adomNode. And you’re not parsing anything. Please don’t use wrong self-documenting variable names.Corrected version:
I would not use trim(), that would produce
<div>Hi<b>I</b>am</div>from<div>Hi <b>I</b> am</div>. You might do something like.replace(/\s+/g, " ").