files/en-us/web/api/sanitizer/replaceelementwithchildren/index.md
{{APIRef("HTML Sanitizer API")}}
The replaceElementWithChildren() method of the {{domxref("Sanitizer")}} interface sets an element to be replaced by its child HTML elements when the sanitizer is used.
This is primarily used for stripping styles from text.
replaceElementWithChildren(element)
element
name
namespace {{optional_inline}}
"http://www.w3.org/1999/xhtml".true if the operation changed the configuration to set the element to be replaced by its children, and false if the sanitizer was already replacing the element.
This example shows the basic usage of the method, configuring a Sanitizer that replaces the <em> element in inputs with its child content.
// Create sanitizer (in this case the default)
const sanitizer = new Sanitizer();
// Replace <em> elements with their innerHTML
sanitizer.replaceElementWithChildren("em");
This example shows how replaceElementWithChildren() can be used to strip styles from text.
<pre id="log"></pre>
#log {
height: 480px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
const logElement = document.querySelector("#log");
function log(text) {
logElement.textContent += text;
}
The code first creates a new Sanitizer object that initially allows {{htmlelement("p")}}, {{htmlelement("em")}}, and {{htmlelement("strong")}} elements.
We then call replaceElementWithChildren() on the sanitizer specifying that <strong> elements should be replaced.
The code defines a string that has <strong> elements and uses {{domxref("Element.setHTML()")}} with the sanitizer to inject the string.
The original string, the sanitized HTML from the element, and the sanitizer are logged.
if ("Sanitizer" in window) {
// Create sanitizer using SanitizerConfig
const sanitizer = new Sanitizer({
elements: ["p", "em", "strong"],
});
// Replace the <strong> element
sanitizer.replaceElementWithChildren("strong");
const unsanitizedString = `<p>This is a with <strong>important</strong> text <em>highlighted</em>.</p>`;
log(`unsanitizedHTMLString:\n ${unsanitizedString}`);
// Create a <div> element
const divElement = document.createElement("div");
divElement.setHTML(unsanitizedString, { sanitizer });
log(`\n\nsanitizedHTML:\n ${divElement.innerHTML}`);
// Log the sanitizer configuration
const sanitizerConfig = sanitizer.get();
log(`\n\nsanitizerConfig:\n ${JSON.stringify(sanitizerConfig, null, 2)}`);
} else {
log("The HTML Sanitizer API is NOT supported in this browser.");
}
The original unsanitized HTML string, the sanitized string from the element, and the sanitizer are logged below.
Note that the <strong> styling is stripped from the text, but the <em> element is not.
Note also that the <strong> element was originally in the elements list in the configuration, but was removed when it was added to the replaceWithChildrenElements list.
{{EmbedLiveSample("How to strip styles from text","100","520px")}}
{{Specifications}}
{{Compat}}