Sanitizer: removeElement() method
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The removeElement() method of the Sanitizer interface sets the specified element be removed from the output when the sanitizer is used.
Syntax
removeElement(element)
Parameters
element-
A string indicating the name of the element to be disallowed, or an object with the following properties:
name-
A string containing the name of the element.
namespaceOptional-
A string containing the namespace of the element. The default namespace is
"http://www.w3.org/1999/xhtml".
Return value
true if the operation changed the configuration to disallow the element, and false if the element was already disallowed.
Note that false might be returned if the internal configuration:
- defines a
elementsarray array and the element is already omitted (it does not need to be removed) - instead defines the
removeElementsarray and the specified element is already present (and is hence already filtered)
Examples
>How to disallow elements
This example shows how removeElement() is used to specify an element to be "disallowed".
JavaScript
The code first creates a new Sanitizer object that initially allows <div> and <script> elements, and that replaces <span> elements with their child elements.
The code then calls removeElement() to add <p>, <script> and <span> elements to the removeElements list in the configuration.
Note that adding <script> and <span> removes the elements from their original lists.
// Create sanitizer using SanitizerConfig
const sanitizer = new Sanitizer({
elements: ["div", "script"],
replaceWithChildrenElements: ["span"],
});
// Disallow the <p> element
sanitizer.removeElement("p");
// Disallow the <script> element
sanitizer.removeElement("script");
// Disallow the <span> element
sanitizer.removeElement("span");
// Log the sanitizer configuration
let sanitizerConfig = sanitizer.get();
log(JSON.stringify(sanitizerConfig, null, 2));
Note:
This configuration is provided for demonstration only.
Sanitizer configurations should include either just the allowed elements (elements) or just the disallowed elements (removeElements), but not both.
In this case only the <div> element is allowed and all other elements will be removed from the input: so the removed elements have no effect.
Results
The final configuration is logged below.
Specifications
| Specification |
|---|
| HTML Sanitizer API> # dom-sanitizer-removeelement> |
Browser compatibility
Loading…