Document:createElement() 方法
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
在 HTML 文件中,document.createElement()
方法會建立由 localName
指定的 HTML 元素,若 localName
無法識別,則會建立 HTMLUnknownElement
。
語法
createElement(localName)
createElement(localName, options)
參數
localName
-
一個字串,指定要建立的元素類型。不要使用限定名稱(例如「html:a」)來呼叫此方法。在 HTML 文件中呼叫時,
createElement()
會將localName
轉換為小寫後再建立元素。在 Firefox、Opera 和 Chrome 中,createElement(null)
的行為與createElement("null")
相同。 options
選擇性-
一個物件,包含以下屬性:
回傳值
新的 Element
。
備註: 如果文件是 HTMLDocument(這是最常見的情況),則會回傳新的 HTMLElement。否則,會回傳新的 Element。
範例
基本範例
此範例會建立一個新的 以下範例片段取自我們的 expanding-list-web-component 範例(也可以查看實際範例)。在此範例中,我們的自訂元素擴展了 如果我們想以程式方式建立此元素的實例,可以使用如下呼叫: 新元素將被賦予一個 備註:
為了與先前版本的自訂元素規範相容,一些瀏覽器允許你在此處傳遞字串,而非物件,該字串的值為自訂元素的標籤名稱。div1
的元素之前。
HTML
JavaScript
document.body.onload = addElement;
function addElement() {
// 建立一個新的 div 元素
const newDiv = document.createElement("div");
// 並為其添加一些內容
const newContent = document.createTextNode("嗨,你好!");
// 將文字節點添加到新建立的 div 中
newDiv.appendChild(newContent);
// 將新建立的元素及其內容插入到 DOM 中
const currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
結果
Web 組件範例
HTMLUListElement
,該元素代表
元素。// 為元素建立一個類別
class ExpandingList extends HTMLUListElement {
constructor() {
// 在建構子中始終先呼叫 super
super();
// 建構子定義省略以簡化
// …
}
}
// 定義新元素
customElements.define("expanding-list", ExpandingList, { extends: "ul" });
let expandingList = document.createElement("ul", { is: "expanding-list" });
is
屬性,其值為自訂元素的標籤名稱。規範
Specification DOM
# ref-for-dom-document-createelement①瀏覽器相容性
參見