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①

浏览器兼容性

另见