Ok, I have the following string
I have a string that contains the following:
<span>A</span>BC<span id="blabla">D<span>EF</span></span>GH
I want to be able to use pure JavaScript to strip out any span tag that does not have an id so that the output looks like:
ABC<span id="blabla">DEF</span>GH
I have the following code which works fine but does not handle the nested span in the middle (the one that holds EF). I just need to know how can I use recursion to accomplish my goal.
function removeSpans2(s) {
var a = document.createElement('div');
a.innerHTML = s;
var node, next = a.firstChild;
while (node = next) {
next = next.nextSibling
if (node.tagName && node.tagName.toLowerCase() == 'span' && !node.id) {
a.replaceChild(document.createTextNode(node.textContent || node.innerText), node);
}
}
return a.innerHTML;
}
No recursion needed, figured out a simpler algorithm. This one handles all sorts of nested elements, you can have A elements inside the spans, or spans in side As, or spans in spans in spans… whatever.