DocumentType: before() 方法

Baseline 已广泛支持

此功能已成熟,可跨多种设备和浏览器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有浏览器中可用。

DocumentType.before() 方法会在 DocumentType 的父节点的所有子节点列表中,在 DocumentType 对象的前面插入一组 Node 对象或字符串。字符串会被插入为等效的 Text 节点。

语法

js
before(param1)
before(param1, param2)
before(param1, param2, /* …, */ paramN)

参数

param1, …, paramN

要插入的一组 Node 对象或字符串。

返回值

无(undefined)。

异常

HierarchyRequestError DOMException

在节点无法插入到层次结构中的指定位置时抛出。

示例

添加条件注释

注释节点可以在 doctype 声明之前有效,但不建议这样做,因为它们会在 IE 中触发怪异模式。 条件注释对 IE 也有效,尽管

js
let docType = document.implementation.createDocumentType("html", "", "");
let myDoc = document.implementation.createDocument("", "", docType);

docType.before(
  document.createComment("<!--[if !IE]> conditional comment <![endif]-->"),
);

myDoc.childNodes;
// NodeList [<!--[if !IE]> conditional comment <![endif]-->, <!DOCTYPE html>]

规范

规范
DOM
# ref-for-dom-childnode-before①

浏览器兼容性

另见