aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/element/innerhtml/index.html
blob: df002176e4aad6db5cef661dcf4c13b4a1830631 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
---
title: Element.innerHTML
slug: Web/API/Element/innerHTML
tags:
  - 元素組件
  - 注譯
  - 裏HTML
  - 裏超文本
translation_of: Web/API/Element/innerHTML
---
<div>{{APIRef("DOM")}}</div>



<p> <a href="/zh-TW/docs/Glossary/Element">Element</a>  的「innerHTML」屬性獲取或設置元素中包含的HTML或XML標記。</p>

<div class="note"><strong>Note:  </strong>{{HTMLElement("div")}}, {{HTMLElement("span")}}, or {{HTMLElement("noembed")}} 節點有包含字符(&),(&lt;)或(&gt;),innerHTML分別地回傳這些字符成為HTML的<code>&amp;</code><code>&lt;</code><code>&gt;</code>。 使用 <code>Node.textContent</code> 得到的這些文本節點的內容的原始拷貝件。</div>

<p>To insert the HTML into the document rather than replace the contents of an element, use the method {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox notranslate">const <var>content</var> = <var>element</var>.innerHTML;

<var>element</var>.innerHTML = <var>htmlString</var>;
</pre>

<h3 id="Value">Value</h3>

<p>A {{domxref("DOMString")}} containing the HTML serialization of the element's descendants. Setting the value of <code>innerHTML</code> removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string <var>htmlString</var>.</p>

<h3 id="Exceptions">Exceptions</h3>

<dl>
 <dt><code>SyntaxError</code></dt>
 <dd>An attempt was made to set the value of <code>innerHTML</code> using a string which is not properly-formed HTML.</dd>
 <dt><code>NoModificationAllowedError</code></dt>
 <dd>An attempt was made to insert the HTML into a node whose parent is a {{domxref("Document")}}.</dd>
</dl>

<h2 id="Usage_notes">Usage notes</h2>

<p>The <code>innerHTML</code> 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.</p>

<h3 id="Reading_the_HTML_contents_of_an_element">Reading the HTML contents of an element</h3>

<p>Reading <code>innerHTML</code> causes the user agent to serialize the HTML or XML fragment comprised of the elment's descendants. The resulting string is returned.</p>

<pre class="brush: js notranslate">let contents = myElement.innerHTML;</pre>

<p>This lets you look at the HTML markup of the element's content nodes.</p>

<div class="note">
<p><strong>Note:</strong> 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.</p>
</div>

<div class="note">
<p><strong>Note:</strong>基於元素的當前內容產生返回的HTML或XML片段,所以返回的片段的標記和格式可能不匹配原始頁面標記。</p>
</div>

<h3 id="Replacing_the_contents_of_an_element">Replacing the contents of an element</h3>

<p>Setting the value of <code>innerHTML</code> lets you easily replace the existing contents of an element with new content.</p>

<p>For example, you can erase the entire contents of a document by clearing the contents of the document's {{domxref("Document.body", "body")}} attribute:</p>

<pre class="brush: js notranslate">document.body.innerHTML = "";</pre>

<p>This example fetches the document's current HTML markup and replaces the <code>"&lt;"</code> characters with the HTML entity <code>"&amp;lt;"</code>, thereby essentially converting the HTML into raw text. This is then wrapped in a {{HTMLElement("pre")}} element. Then the value of <code>innerHTML</code> is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.</p>

<pre class="brush: js notranslate">document.documentElement.innerHTML = "&lt;pre&gt;" +
         document.documentElement.innerHTML.replace(/&lt;/g,"&amp;lt;") +
            "&lt;/pre&gt;";</pre>

<h4 id="Operational_details">Operational details</h4>

<p>What exactly happens when you set value of <code>innerHTML</code>? Doing so causes the user agent to follow these steps:</p>

<ol>
 <li>The specified value is parsed as HTML or XML (based on the document type), resulting in a {{domxref("DocumentFragment")}} object representing the new set of DOM nodes for the new elements.</li>
 <li>If the element whose contents are being replaced is a {{HTMLElement("template")}} element, then the <code>&lt;template&gt;</code> element's {{domxref("HTMLTemplateElement.content", "content")}} attribute is replaced with the new <code>DocumentFragment</code> created in step 1.</li>
 <li>For all other elements, the element's contents are replaced with the nodes in the new <code>DocumentFragment</code>.</li>
</ol>

<h3 id="Security_considerations">Security considerations</h3>

<p>It is not uncommon to see <code>innerHTML</code> 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.</p>

<pre class="brush: js notranslate">const name = "John";
// assuming 'el' is an HTML DOM element
el.innerHTML = name; // harmless in this case

// ...

name = "&lt;script&gt;alert('I am John in an annoying alert!')&lt;/script&gt;";
el.innerHTML = name; // harmless in this case</pre>

<p>Although this may look like a {{interwiki("wikipedia", "cross-site scripting")}} attack, the result is harmless. HTML5 specifies that a {{HTMLElement("script")}} tag inserted with <code>innerHTML</code> <a href="https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0">should not execute</a>.</p>

<p>However, there are ways to execute JavaScript without using {{HTMLElement("script")}} elements, so there is still a security risk whenever you use <code>innerHTML</code> to set strings over which you have no control. For example:</p>

<pre class="brush: js notranslate">const name = "&lt;img src='x' onerror='alert(1)'&gt;";
el.innerHTML = name; // shows the alert</pre>

<p>For that reason, it is recommended that you do not use <code>innerHTML</code> when inserting plain text; instead, use {{domxref("Node.textContent")}}. This doesn't parse the passed content as HTML, but instead inserts it as raw text.</p>

<div class="warning">
<p><strong>Warning:</strong> If your project is one that will undergo any form of security review, using <code>innerHTML</code> most likely will result in your code being rejected. For example, <a href="https://wiki.mozilla.org/Add-ons/Reviewers/Guide/Reviewing#Step_2:_Automatic_validation">if you use <code>innerHTML</code></a> in a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions">browser extension</a> and submit the extension to <a href="https://addons.mozilla.org/">addons.mozilla.org</a>, it will not pass the automated review process.</p>
</div>

<h2 id="Example">Example</h2>

<p>This example uses <code>innerHTML</code> to create a mechanism for logging messages into a box on a web page.</p>

<h3 id="JavaScript">JavaScript</h3>

<pre class="brush: js notranslate">function log(msg) {
  var logElem = document.querySelector(".log");

  var time = new Date();
  var timeStr = time.toLocaleTimeString();
  logElem.innerHTML += timeStr + ": " + msg + "&lt;br/&gt;";
}

log("Logging mouse events inside this container...");
</pre>

<p>The <code>log()</code> function creates the log output by getting the current time from a {{jsxref("Date")}} object using {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}}, and building a string with the timestamp and the message text. Then the message is appended to the box with the class <code>"log"</code>.</p>

<p>We add a second method that logs information about {{domxref("MouseEvent")}} based events (such as {{event("mousedown")}}, {{event("click")}}, and {{event("mouseenter")}}):</p>

<pre class="brush: js notranslate">function logEvent(event) {
  var msg = "Event &lt;strong&gt;" + event.type + "&lt;/strong&gt; at &lt;em&gt;" +
            event.clientX + ", " + event.clientY + "&lt;/em&gt;";
  log(msg);
}</pre>

<p>Then we use this as the event handler for a number of mouse events on the box that contains our log:</p>

<pre class="brush: js notranslate">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);</pre>

<h3 id="HTML">HTML</h3>

<p>The HTML is quite simple for our example.</p>

<pre class="brush: html notranslate">&lt;div class="box"&gt;
  &lt;div&gt;&lt;strong&gt;Log:&lt;/strong&gt;&lt;/div&gt;
  &lt;div class="log"&gt;&lt;/div&gt;
&lt;/div&gt;</pre>

<p>The {{HTMLElement("div")}} with the class <code>"box"</code> is just a container for layout purposes, presenting the contents with a box around it. The <code>&lt;div&gt;</code> whose class is <code>"log"</code> is the container for the log text itself.</p>

<h3 id="CSS">CSS</h3>

<p>The following CSS styles our example content.</p>

<pre class="brush: css notranslate">.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;
}</pre>

<h3 id="Result">Result</h3>

<p>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.</p>

<p>{{EmbedLiveSample("Example", 640, 350)}}</p>

<h2 id="Specification">Specification</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}</td>
   <td>{{Spec2('DOM Parsing')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<p>{{Compat("api.Element.innerHTML")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{domxref("Node.textContent")}} and {{domxref("Node.innerText")}}</li>
 <li>{{domxref("Element.insertAdjacentHTML()")}}</li>
 <li>Parsing HTML into a DOM tree: {{domxref("DOMParser")}}</li>
 <li>Serializing XML or HTML into a DOM tree: {{domxref("XMLSerializer")}}</li>
</ul>