Sanitizer: removeElement() method

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 an element to be disallowed — removed from input when the sanitizer is used.

The specified element is added to the list of removeElements in this sanitizer's configuration. The element is removed from the elements or replaceWithChildrenElements lists if present.

Syntax

js
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.

namespace Optional

A string containing the namespace of the element. The default namespace is "http://www.w3.org/1999/xhtml".

Returns

None (undefined).

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.

js
// 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