元素
property
innerHTML
获取或设置包含在元素中的 HTML 或 XML 标记。
<div>
,
<span>
,或
<noembed>
节点有子级文本节点,其包括字符
(&)
,
(<)
,或
(>)
,
innerHTML
返回这些字符作为 HTML 实体
"&"
,
"<"
and
">"
分别。使用
Node.textContent
以获取这些文本节点内容的原生副本。
要把 HTML 插入文档而不是替换元素内容,使用方法
insertAdjacentHTML()
.
const content = element.innerHTML; element.innerHTML = htmlString;
A
DOMString
containing the HTML serialization of the element's descendants. Setting the value of
innerHTML
removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string
htmlString
.
SyntaxError
innerHTML
using a string which is not properly-formed HTML.
NoModificationAllowedError
Document
.
innerHTML
property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.
Reading
innerHTML
causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.
let contents = myElement.innerHTML;
This lets you look at the HTML markup of the element's content nodes.
注意: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
Setting the value of
innerHTML
lets you easily replace the existing contents of an element with new content.
For example, you can erase the entire contents of a document by clearing the contents of the document's
body
属性:
document.body.innerHTML = "";
This example fetches the document's current HTML markup and replaces the
"<"
characters with the HTML entity
"<"
, thereby essentially converting the HTML into raw text. This is then wrapped in a
<pre>
element. Then the value of
innerHTML
is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.
document.documentElement.innerHTML = "<pre>" +
document.documentElement.innerHTML.replace(/</g,"<") +
"</pre>";
What exactly happens when you set value of
innerHTML
? Doing so causes the user agent to follow these steps:
DocumentFragment
object representing the new set of DOM nodes for the new elements.
<template>
element, then the
<template>
元素的
content
attribute is replaced with the new
DocumentFragment
created in step 1.
DocumentFragment
.
It is not uncommon to see
innerHTML
used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.
const name = "John";
// assuming 'el' is an HTML DOM element
el.innerHTML = name; // harmless in this case
// ...
name = "<script>alert('I am John in an annoying alert!')</script>";
el.innerHTML = name; // harmless in this case
Although this may look like a
cross-site scripting
attack, the result is harmless. HTML5 specifies that a
<script>
tag inserted with
innerHTML
should not execute
.
However, there are ways to execute JavaScript without using
<script>
elements, so there is still a security risk whenever you use
innerHTML
to set strings over which you have no control. For example:
const name = "<img src='x' onerror='alert(1)'>"; el.innerHTML = name; // shows the alert
For that reason, it is recommended that you do not use
innerHTML
when inserting plain text; instead, use
Node.textContent
. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
警告:
If your project is one that will undergo any form of security review, using
innerHTML
most likely will result in your code being rejected. For example,
if you use
innerHTML
在
browser extension
and submit the extension to
addons.mozilla.org
, it will not pass the automated review process.
此范例使用
innerHTML
to create a mechanism for logging messages into a box on a web page.
function log(msg) {
var logElem = document.querySelector(".log");
var time = new Date();
var timeStr = time.toLocaleTimeString();
logElem.innerHTML += timeStr + ": " + msg + "<br/>";
}
log("Logging mouse events inside this container...");
log()
function creates the log output by getting the current time from a
日期
对象使用
toLocaleTimeString()
, and building a string with the timestamp and the message text. Then the message is appended to the box with the class
"log"
.
We add a second method that logs information about
MouseEvent
based events (such as
mousedown
,
click
,和
mouseenter
):
function logEvent(event) {
var msg = "Event <strong>" + event.type + "</strong> at <em>" +
event.clientX + ", " + event.clientY + "</em>";
log(msg);
}
Then we use this as the event handler for a number of mouse events on the box that contains our log:
var boxElem = document.querySelector(".box");
boxElem.addEventListener("mousedown", logEvent);
boxElem.addEventListener("mouseup", logEvent);
boxElem.addEventListener("click", logEvent);
boxElem.addEventListener("mouseenter", logEvent);
boxElem.addEventListener("mouseleave", logEvent);
The HTML is quite simple for our example.
<div class="box"> <div><strong>Log:</strong></div> <div class="log"></div> </div>
<div>
with the class
"box"
is just a container for layout purposes, presenting the contents with a box around it. The
<div>
whose class is
"log"
is the container for the log text itself.
The following CSS styles our example content.
.box {
width: 600px;
height: 300px;
border: 1px solid black;
padding: 2px 4px;
overflow-y: scroll;
overflow-x: auto;
}
.log {
margin-top: 8px;
font-family: monospace;
}
The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM 剖析和序列化
The definition of 'Element.innerHTML' in that specification. |
工作草案 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
innerHTML
|
Chrome
33
|
Edge 12 | Firefox 1 | IE 4 | Opera 8 | Safari 9 |
WebView Android
4.4
|
Chrome Android
33
|
Firefox Android 4 | Opera Android 10.1 | Safari iOS 9 |
Samsung Internet Android
2.0
|
完整支持
见实现注意事项。
Node.textContent
and
Node.innerText
Element.insertAdjacentHTML()
Element.outerHTML
DOMParser
XMLSerializer
元素
accessKey
属性
childElementCount
children
classList
className
clientHeight
clientLeft
clientTop
clientWidth
currentStyle
firstElementChild
id
innerHTML
lastElementChild
localName
名称
namespaceURI
nextElementSibling
onfullscreenchange
onfullscreenerror
openOrClosedShadowRoot
outerHTML
part
prefix
previousElementSibling
runtimeStyle
scrollHeight
scrollLeft
scrollLeftMax
scrollTop
scrollTopMax
scrollWidth
shadowRoot
slot
tabStop
tagName
after()
animate()
append()
attachShadow()
before()
closest()
computedStyleMap()
createShadowRoot()
getAnimations()
getAttribute()
getAttributeNames()
getAttributeNode()
getAttributeNodeNS()
getAttributeNS()
getBoundingClientRect()
getClientRects()
getElementsByClassName()
getElementsByTagName()
getElementsByTagNameNS()
hasAttribute()
hasAttributeNS()
hasAttributes()
hasPointerCapture()
insertAdjacentElement()
insertAdjacentHTML()
insertAdjacentText()
matches()
msZoomTo()
prepend()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
releasePointerCapture()
remove()
removeAttribute()
removeAttributeNode()
removeAttributeNS()
replaceChildren()
replaceWith()
requestFullscreen()
requestPointerLock()
scroll()
scrollBy()
scrollIntoView()
scrollIntoViewIfNeeded()
scrollTo()
setAttribute()
setAttributeNode()
setAttributeNodeNS()
setAttributeNS()
setCapture()
setPointerCapture()
toggleAttribute()
afterscriptexecute
auxclick
blur
click
compositionend
compositionstart
compositionupdate
contextmenu
copy
cut
dblclick
DOMActivate
DOMMouseScroll
error
focus
focusin
focusout
fullscreenchange
fullscreenerror
gesturechange
gestureend
gesturestart
keydown
keypress
keyup
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel
MozMousePixelScroll
msContentZoom
MSGestureChange
MSGestureEnd
MSGestureHold
MSGestureStart
MSGestureTap
MSInertiaStart
MSManipulationStateChanged
overflow
paste
scroll
select
show
touchcancel
touchend
touchmove
touchstart
underflow
webkitmouseforcechanged
webkitmouseforcedown
webkitmouseforceup
webkitmouseforcewillbegin
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
Document
DocumentFragment
DocumentType
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument