Sanitizer: replaceElementWithChildren() 方法
replaceElementWithChildren()
方法是 Sanitizer
接口的一个方法,它会设置一个元素,在 sanitizer 使用时,该元素将被其子 HTML 元素替换。该方法主要用于剥离文本中的样式。
指定的元素及其命名空间会被添加到此 sanitizer 配置的 replaceWithChildrenElements
列表中。如果元素存在于 elements
或 removeElements
列表中,则会被移除。
语法
replaceElementWithChildren(element)
参数
element
-
一个字符串,表示要被替换的元素的名称,或者一个具有以下属性的对象
name
-
一个包含元素名称的字符串。
namespace
可选-
一个包含元素命名空间的字符串。默认命名空间为
"http://www.w3.org/1999/xhtml"
。
返回值
无 (undefined
)。
示例
基本用法
此示例展示了该方法的基本用法,配置了一个 sanitizer,该 sanitizer 会将输入中的 <em>
元素替换为其子内容。
// Create sanitizer (in this case the default)
const sanitizer = new Sanitizer();
// Replace <em> elements with their innerHTML
sanitizer.replaceElementWithChildren("em");
如何剥离文本中的样式
此示例展示了如何使用 replaceElementWithChildren()
来剥离文本中的样式。
JavaScript
代码首先创建一个新的 Sanitizer
对象,该对象最初允许 <p>
、<em>
和 <strong>
元素。然后,我们在 sanitizer 上调用 replaceElementWithChildren()
,指定 <strong>
元素应该被替换。
代码定义了一个包含 <strong>
元素的字符串,并使用带有 sanitizer 的 Element.setHTML()
来注入该字符串。然后会记录原始字符串、来自元素的已净化 HTML 以及 sanitizer。
// 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)}`);
结果
下面记录了原始的未净化 HTML 字符串、来自元素的已净化字符串以及 sanitizer。请注意,文本中的 <strong>
样式已被剥离,但 <em>
元素没有。同时请注意,<strong>
元素最初位于配置的 elements
列表中,但在被添加到 replaceWithChildrenElements
列表时被移除了。
规范
规范 |
---|
HTML Sanitizer API # dom-sanitizer-replaceelementwithchildren |
浏览器兼容性
加载中…