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①

瀏覽器相容性

另見