元素 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
An attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
NoModificationAllowedError
An attempt was made to insert the HTML into a node whose parent is a 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.

读取元素的 HTML 内容

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:

  1. The specified value is parsed as HTML or XML (based on the document type), resulting in a DocumentFragment object representing the new set of DOM nodes for the new elements.
  2. If the element whose contents are being replaced is a <template> element, then the <template> 元素的 content attribute is replaced with the new DocumentFragment created in step 1.
  3. For all other elements, the element's contents are replaced with the nodes in the new 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.

JavaScript

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);
					

HTML

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.

CSS

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.
工作草案 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
innerHTML Chrome 33
33
This API was previously available on the 节点 API。
Edge 12 Firefox 1 IE 4 Opera 8 Safari 9 WebView Android 4.4
4.4
This API was previously available on the 节点 API。
Chrome Android 33
33
This API was previously available on the 节点 API。
Firefox Android 4 Opera Android 10.1 Safari iOS 9 Samsung Internet Android 2.0
2.0
This API was previously available on the 节点 API。

图例

完整支持

完整支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. DOM (文档对象模型)
  2. 元素
  3. 特性
    1. accessKey
    2. 属性
    3. childElementCount
    4. children
    5. classList
    6. className
    7. clientHeight
    8. clientLeft
    9. clientTop
    10. clientWidth
    11. currentStyle
    12. firstElementChild
    13. id
    14. innerHTML
    15. lastElementChild
    16. localName
    17. 名称
    18. namespaceURI
    19. nextElementSibling
    20. onfullscreenchange
    21. onfullscreenerror
    22. openOrClosedShadowRoot
    23. outerHTML
    24. part
    25. prefix
    26. previousElementSibling
    27. runtimeStyle
    28. scrollHeight
    29. scrollLeft
    30. scrollLeftMax
    31. scrollTop
    32. scrollTopMax
    33. scrollWidth
    34. shadowRoot
    35. slot
    36. tabStop
    37. tagName
  4. 方法
    1. after()
    2. animate()
    3. append()
    4. attachShadow()
    5. before()
    6. closest()
    7. computedStyleMap()
    8. createShadowRoot()
    9. getAnimations()
    10. getAttribute()
    11. getAttributeNames()
    12. getAttributeNode()
    13. getAttributeNodeNS()
    14. getAttributeNS()
    15. getBoundingClientRect()
    16. getClientRects()
    17. getElementsByClassName()
    18. getElementsByTagName()
    19. getElementsByTagNameNS()
    20. hasAttribute()
    21. hasAttributeNS()
    22. hasAttributes()
    23. hasPointerCapture()
    24. insertAdjacentElement()
    25. insertAdjacentHTML()
    26. insertAdjacentText()
    27. matches()
    28. msZoomTo()
    29. prepend()
    30. querySelector()
    31. querySelector()
    32. querySelectorAll()
    33. querySelectorAll()
    34. releasePointerCapture()
    35. remove()
    36. removeAttribute()
    37. removeAttributeNode()
    38. removeAttributeNS()
    39. replaceChildren()
    40. replaceWith()
    41. requestFullscreen()
    42. requestPointerLock()
    43. scroll()
    44. scrollBy()
    45. scrollIntoView()
    46. scrollIntoViewIfNeeded()
    47. scrollTo()
    48. setAttribute()
    49. setAttributeNode()
    50. setAttributeNodeNS()
    51. setAttributeNS()
    52. setCapture()
    53. setPointerCapture()
    54. toggleAttribute()
  5. 事件
    1. afterscriptexecute
    2. auxclick
    3. blur
    4. click
    5. compositionend
    6. compositionstart
    7. compositionupdate
    8. contextmenu
    9. copy
    10. cut
    11. dblclick
    12. DOMActivate
    13. DOMMouseScroll
    14. error
    15. focus
    16. focusin
    17. focusout
    18. fullscreenchange
    19. fullscreenerror
    20. gesturechange
    21. gestureend
    22. gesturestart
    23. keydown
    24. keypress
    25. keyup
    26. mousedown
    27. mouseenter
    28. mouseleave
    29. mousemove
    30. mouseout
    31. mouseover
    32. mouseup
    33. mousewheel
    34. MozMousePixelScroll
    35. msContentZoom
    36. MSGestureChange
    37. MSGestureEnd
    38. MSGestureHold
    39. MSGestureStart
    40. MSGestureTap
    41. MSInertiaStart
    42. MSManipulationStateChanged
    43. overflow
    44. paste
    45. scroll
    46. select
    47. show
    48. touchcancel
    49. touchend
    50. touchmove
    51. touchstart
    52. underflow
    53. webkitmouseforcechanged
    54. webkitmouseforcedown
    55. webkitmouseforceup
    56. webkitmouseforcewillbegin
    57. wheel
  6. 继承:
    1. 节点
    2. EventTarget
  7. DOM 相关页面
    1. AbortController
    2. AbortSignal
    3. AbstractRange
    4. Attr
    5. ByteString
    6. CDATASection
    7. CSSPrimitiveValue
    8. CSSValue
    9. CSSValueList
    10. CharacterData
    11. ChildNode
    12. 注释
    13. CustomEvent
    14. DOMConfiguration
    15. DOMError
    16. DOMErrorHandler
    17. DOMException
    18. DOMImplementation
    19. DOMImplementationList
    20. DOMImplementationRegistry
    21. DOMImplementationSource
    22. DOMLocator
    23. DOMObject
    24. DOMParser
    25. DOMPoint
    26. DOMPointInit
    27. DOMPointReadOnly
    28. DOMRect
    29. DOMString
    30. DOMTimeStamp
    31. DOMTokenList
    32. DOMUserData
    33. Document
    34. DocumentFragment
    35. DocumentType
    36. ElementTraversal
    37. Entity
    38. EntityReference
    39. 事件
    40. EventTarget
    41. HTMLCollection
    42. MutationObserver
    43. 节点
    44. NodeFilter
    45. NodeIterator
    46. NodeList
    47. NonDocumentTypeChildNode
    48. ProcessingInstruction
    49. PromiseResolver
    50. 范围
    51. StaticRange
    52. 文本
    53. TextDecoder
    54. TextEncoder
    55. TimeRanges
    56. TreeWalker
    57. TypeInfo
    58. USVString
    59. UserDataHandler
    60. XMLDocument

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1