In an
HTML
document, the
document.createElement()
method creates the HTML element specified by
tagName
,或
HTMLUnknownElement
if
tagName
isn't recognized.
let element = document.createElement(tagName[, options]);
nodeName
of the created element is initialized with the value of
tagName
. Don't use qualified names (like "html:a") with this method. When called on an HTML document,
createElement()
converts
tagName
to lower case before creating the element. In Firefox, Opera, and Chrome,
createElement(null)
works like
createElement("null")
.
ElementCreationOptions
object, containing a single property named
is
, whose value is the tag name of a custom element previously defined via
customElements.define()
。见
Web component example
了解更多细节。
新的
元素
.
This creates a new
<div>
and inserts it before the element with the ID "
div1
".
<!DOCTYPE html> <html> <head> <title>||Working with elements||</title> </head> <body> <div id="div1">The text above has been created dynamically.</div> </body> </html>
document.body.onload = addElement;
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);
}
The following example snippet is taken from our expanding-list-web-component example (see it live also). In this case, our custom element extends the
HTMLUListElement
, which represents the
<ul>
元素。
// 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" });
If we wanted to create an instance of this element programmatically, we'd use a call along the following lines:
let expandingList = document.createElement('ul', { is : 'expanding-list' })
The new element will be given an
is
attribute whose value is the custom element's tag name.
注意 : For backwards compatibility with previous versions of the Custom Elements specification , some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name.
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'Document.createElement' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
createElement
|
Chrome 1 | Edge 12 |
Firefox
1
|
IE 5 | Opera 6 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
选项
参数
|
Chrome
Yes
|
Edge
79
|
Firefox
50
|
IE No |
Opera
Yes
|
Safari No |
WebView Android
Yes
|
Chrome Android
Yes
|
Firefox Android
50
|
Opera Android
Yes
|
Safari iOS No |
Samsung Internet Android
Yes
|
完整支持
不支持
见实现注意事项。
Node.removeChild()
Node.replaceChild()
Node.appendChild()
Node.insertBefore()
Node.hasChildNodes()
document.createElementNS()
— to explicitly specify the namespace URI for the element.
Document
alinkColor
all
anchors
applets
bgColor
body
characterSet
childElementCount
children
compatMode
contentType
currentScript
defaultView
designMode
dir
doctype
documentElement
documentURI
documentURIObject
domain
domConfig
嵌入
fgColor
firstElementChild
forms
fullscreen
fullscreenEnabled
head
height
hidden
图像
实现
lastElementChild
lastModified
lastStyleSheetSet
linkColor
链接
location
mozSyntheticDocument
onabort
onafterscriptexecute
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onbeforescriptexecute
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
onfullscreenchange
onfullscreenerror
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onoffline
ononline
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onvisibilitychange
onwheel
origin
plugins
popupNode
preferredStyleSheetSet
readyState
referrer
rootElement
脚本
scrollingElement
selectedStyleSheetSet
styleSheetSets
timeline
title
tooltipNode
URL
visibilityState
vlinkColor
width
xmlEncoding
xmlVersion
adoptNode()
append()
caretRangeFromPoint()
clear()
close()
createAttribute()
createCDATASection()
createComment()
createDocumentFragment()
createElement()
createElementNS()
createEntityReference()
createEvent()
createExpression()
createExpression()
createNodeIterator()
createNSResolver()
createNSResolver()
createProcessingInstruction()
createRange()
createTextNode()
createTouch()
createTouchList()
createTreeWalker()
enableStyleSheetsForSet()
evaluate()
evaluate()
execCommand()
exitFullscreen()
exitPointerLock()
getAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
hasFocus()
hasStorageAccess()
importNode()
mozSetImageElement()
open()
prepend()
queryCommandEnabled()
queryCommandSupported()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
registerElement()
releaseCapture()
replaceChildren()
requestStorageAccess()
write()
writeln()
animationcancel
animationend
animationiteration
animationstart
copy
cut
DOMContentLoaded
drag
dragend
dragenter
dragexit
dragleave
dragover
dragstart
drop
fullscreenchange
fullscreenerror
gotpointercapture
keydown
keypress
keyup
lostpointercapture
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointerlockchange
pointerlockerror
pointermove
pointerout
pointerover
pointerup
readystatechange
scroll
selectionchange
selectstart
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
visibilitychange
wheel
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument