The institution I work for uses an application that has an awful software bug causing useless <code>span</code>
tags to appear next to "misspelled" words in iframes.
For instance, HTML that should look like this:
<span class="myClass">Hello! My name is Tabitha.</span>
...might look like this instead:
<span class="myClass">Hello! My name is <span><span><span><span><span>Tabitha.</span></span></span></span></span></span>
My band-aid solution, while we wait for a fix from the application developer, has been to add a script that finds all attribute-less span
tags and replaces them with a new <code>textNode</code>
. This works because these extra tags are always the direct parent of the <code>textNode</code>
containing the misspelled word (or another extra span
element). Any formatting or inline styling would occur outside that scope and would thus be unaffected.
But, something tells me there's got to be a better way to do it. Any thoughts?
function fixSpan(iframe) {
var doc = iframe.contentDocument;
var spans = doc.getElementsByTagName('span'); //find all <span> elements
for (var i = 0; i < spans.length; i++) {
var span = spans[i];
var tag = span.outerHTML.slice(0,6);
if (tag === '<span>') { //if the span has no attributes
//replace it with a new textNode containing its textContent
console.log('FOUND: <span>' + span.textContent + '</span>');
span.parentNode.replaceChild(document.createTextNode(span.textContent), span);
}
}
if (doc.documentElement.innerHTML.includes('<span>')) {
//if any attribute-less tags remain, run the method again
console.log('Fix not complete, re-running...');
fixSpan(iframe);
} else {
console.log('Fix complete.');
}
}