Created
July 22, 2016 17:01
-
-
Save rvighne/b8ef51255f821d4dd79c32f470511b5c to your computer and use it in GitHub Desktop.
Easy-to-use and robust function that removes all HTML formatting from an element by replacing its contents with a single Text node. This does not remove any CSS styling applied to the parent element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
USAGE: | |
void removeFormatting(Element) | |
RESULT: | |
The provided element now contains a single Text node, whose value is | |
the concatenation of all the Text nodes in the original element's hierarchy | |
*/ | |
// Used internally. Empties the element and returns the concatenated text as a String | |
function _removeFormatting(el) { | |
var text = ""; | |
var child; | |
while (child = el.firstChild) { | |
if (child.nodeType === Node.TEXT_NODE) | |
text += child.nodeValue; | |
else if (child.nodeType === Node.ELEMENT_NODE) | |
text += _removeFormatting(child); | |
el.removeChild(child); | |
} | |
return text; | |
} | |
function removeFormatting(el) { | |
el.appendChild(document.createTextNode(_removeFormatting(el))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment