Document: createElement() 方法

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

HTML 文件中,document.createElement() 方法建立由 localName 指定的 HTML 元素,如果 localName 未被識別,則建立一個 HTMLUnknownElement

語法

js
createElement(localName)
createElement(localName, options)

引數

localName

一個字串,指定要建立的元素型別。不要在此方法中使用限定名稱(例如 “html:a”)。在 HTML 文件上呼叫時,createElement() 會在建立元素之前將 localName 轉換為小寫。在 Firefox、Opera 和 Chrome 中,createElement(null) 的作用類似於 createElement("null")

options 可選

具有以下屬性的物件:

is

透過 customElements.define() 預先定義的自定義元素的標籤名稱。有關更多詳細資訊,請參閱Web 元件示例

返回值

新的 Element

注意: 如果文件是 HTMLDocument(最常見的情況),則返回一個新的 HTMLElement。否則返回一個新的 Element

示例

基本示例

這將建立一個新的 <div> 並將其插入到 ID 為 div1 的元素之前。

HTML

html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Working with elements</title>
  </head>
  <body>
    <div id="div1">The text above has been created dynamically.</div>
  </body>
</html>

JavaScript

js
function addElement() {
  // create a new div element
  const newDiv = document.createElement("div");

  // and give it some content
  const newContent = document.createTextNode("Hi there and greetings!");

  // add the text node to the newly created div
  newDiv.appendChild(newContent);

  // add the newly created element and its content into the DOM
  const currentDiv = document.getElementById("div1");
  document.body.insertBefore(newDiv, currentDiv);
}

addElement();

結果

Web 元件示例

注意: 請查閱瀏覽器相容性部分以瞭解支援情況,並查閱 is 屬性參考,以瞭解定製內建元素實現現實中的注意事項。

以下示例片段取自我們的 expanding-list-web-component 示例(也可線上檢視)。在此示例中,我們的自定義元素擴充套件了 HTMLUListElement,它代表 <ul> 元素。

js
// Create a class for the element
class ExpandingList extends HTMLUListElement {
  constructor() {
    // Always call super first in constructor
    super();

    // constructor definition left out for brevity
    // …
  }
}

// Define the new element
customElements.define("expanding-list", ExpandingList, { extends: "ul" });

如果我們要以程式設計方式建立此元素的例項,我們將使用以下程式碼行:

js
let expandingList = document.createElement("ul", { is: "expanding-list" });

新元素將被賦予一個 is 屬性,其值是自定義元素的標籤名。

注意: 為了向後相容,一些瀏覽器將允許你在此處傳遞一個字串而不是一個物件,其中字串的值是自定義元素的標籤名稱。

規範

規範
DOM
# ref-for-dom-document-createelement①

瀏覽器相容性

另見