Document: createElement() 方法
Baseline 广泛可用 *
在 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可选-
具有以下属性的对象:
返回值
新的 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 组件示例
以下示例片段取自我们的 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① |
浏览器兼容性
加载中…