- JavaScript HTML DOM — Changing HTML
- Changing HTML Content
- Example
- Example
- Changing the Value of an Attribute
- Example
- Dynamic HTML content
- Example
- document.write()
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Element: innerHTML property
- Value
- Exceptions
- Usage notes
- Reading the HTML contents of an element
- Replacing the contents of an element
- Operational details
- Appending HTML to an element
- HTML
- JavaScript
- Security considerations
- Examples
- JavaScript
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- HTML DOM Element innerHTML
- See Also:
- The Differences Between innerHTML, innerText and textContent
- Syntax
- Property Value
- Return Value
- More Examples
- Example
- Example
- Example
- The Differences Between innerHTML, innerText and textContent
- HTML Example
- JavaScript Examples
- Browser Support
- Свойство innerHTML
- Определение и использование
- Поддержка браузера
- Синтаксис
- Свойство значений
- Технические детали
- Ещё примеры
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример
- Упражнения
- КАК СДЕЛАТЬ
- ПОДЕЛИТЬСЯ
- СЕРТИФИКАТЫ
- Сообщить об ошибке
- Ваше предложение:
- Спасибо, за вашу помощь!
- Топ Учебники
- Топ Справочники
- Топ Примеры
- Веб Сертификаты
JavaScript HTML DOM — Changing HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a
element:
Example
- The HTML document above contains a
element with id=»p1″
- We use the HTML DOM to get the element with id=»p1″
- A JavaScript changes the content ( innerHTML ) of that element to «New text!»
This example changes the content of an element:
Example
- The HTML document above contains an element with id=»id01″
- We use the HTML DOM to get the element with id=»id01″
- A JavaScript changes the content ( innerHTML ) of that element to «New Heading»
Changing the Value of an Attribute
To change the value of an HTML attribute, use this syntax:
This example changes the value of the src attribute of an element:
Example
- The HTML document above contains an element with id=»myImage»
- We use the HTML DOM to get the element with id=»myImage»
- A JavaScript changes the src attribute of that element from «smiley.gif» to «landscape.jpg»
Dynamic HTML content
JavaScript can create dynamic HTML content:
Example
document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
Never use document.write() after the document is loaded. It will overwrite the document.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Element: innerHTML property
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
Value
A string 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.
Exceptions
Thrown if an attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
Thrown if an attempt was made to insert the HTML into a node whose parent is a Document .
Usage notes
The 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 the HTML contents of an element
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.
Note: 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.
Replacing the contents of an element
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.
Note: This is a security risk if the string to be inserted might contain potentially malicious content. When inserting user-supplied data you should always consider using Element.setHTML() instead, in order to sanitize the content before it is inserted.
For example, you can erase the entire contents of a document by clearing the contents of the document’s body attribute:
This example fetches the document’s current HTML markup and replaces the »
.documentElement.innerHTML = ` $document.documentElement.innerHTML.replace( //g, "<", )> `;
Operational details
What exactly happens when you set value of innerHTML ? Doing so causes the user agent to follow these steps:
- 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.
- If the element whose contents are being replaced is a element, then the element’s content attribute is replaced with the new DocumentFragment created in step 1.
- For all other elements, the element’s contents are replaced with the nodes in the new DocumentFragment .
Appending HTML to an element
Setting the value of innerHTML lets you append new contents to the existing one of an element.
HTML
ul id="list"> li>a href="#">Item 1a>li> li>a href="#">Item 2a>li> li>a href="#">Item 3a>li> ul>
JavaScript
Please note that using innerHTML to append HTML elements (e.g. el.innerHTML += «link» ) will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won’t be able to listen to the previously set event listeners.
Security considerations
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.
let name = "John"; // assuming 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // … name = ""; el.innerHTML = name; // harmless in this case
Although this may look like a cross-site scripting attack, the result is harmless. HTML specifies that a tag inserted with innerHTML should not execute.
const name = ""; el.innerHTML = name; // shows the alert
For that reason, it is recommended that instead of innerHTML you use:
- Element.setHTML() to sanitize the text before it is inserted into the DOM.
- Node.textContent when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.
Warning: 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 in a browser extension and submit the extension to addons.mozilla.org, it may be rejected in the review process. Please see Safely inserting external content into a page for alternative methods.
Examples
This example uses innerHTML to create a mechanism for logging messages into a box on a web page.
JavaScript
function log(msg) const logElem = document.querySelector(".log"); const time = new Date(); const timeStr = time.toLocaleTimeString(); logElem.innerHTML += `$timeStr>: $msg>
`; > log("Logging mouse events inside this container…");
The log() function creates the log output by getting the current time from a Date object using 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 , and mouseenter ):
function logEvent(event) const msg = `Event $event.type> at $event.clientX>, $event.clientY> `; log(msg); >
Then we use this as the event handler for a number of mouse events on the box that contains our log:
const 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>
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; >
Result
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.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Node.textContent and HTMLElement.innerText
- Element.insertAdjacentHTML()
- Element.outerHTML
- Element.setHTML
- Parsing HTML or XML into a DOM tree: DOMParser
- Serializing a DOM tree into an XML string: XMLSerializer
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
HTML DOM Element innerHTML
The innerHTML property sets or returns the HTML content (inner HTML) of an element.
See Also:
The Differences Between
innerHTML, innerText and textContent
Syntax
Return the innerHTML property:
Set the innerHTML property:
Property Value
Return Value
More Examples
Example
Change the HTML content of two elements:
let text = «Hello Dolly.»;
document.getElementById(«myP»).innerHTML = text;
document.getElementById(«myDIV»).innerHTML = text;
Example
Repeat the HTML content of an element:
Example
Change the HTML content and URL of a link:
The Differences Between
innerHTML, innerText and textContent
The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. |
The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except and elements. |
The textContent property returns: The text content of the element and all descendaces, with spacing and CSS hidden text, but without tags. |
HTML Example
JavaScript Examples
let text = document.getElementById(«myP»).innerText;
let text = document.getElementById(«myP»).innerHTML;
let text = document.getElementById(«demo»).textContent;
The innerText property returns: This element has extra spacing and contains a span element. |
The innerHTML property returns: This element has extra spacing and contains a span element. |
The textContent property returns: This element has extra spacing and contains a span element. |
Browser Support
element.innerHTML is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Свойство innerHTML
Дополнительные примеры «Попробуй сам» приведены ниже.
Определение и использование
Свойство innerHTML задает или возвращает HTML-содержимое (innerHTML) элемента.
Поддержка браузера
Синтаксис
Возвращает свойство innerHTML:
Установит свойство innerHTML:
Свойство значений
Технические детали
Ещё примеры
Пример
Получите HTML-содержимое элемента
с помощью >
Пример
Пример
Измените HTML-содержимое двух элементов:
document.getElementById(«myP»).innerHTML = «Привет Андрей.»;
document.getElementById(«myDIV»).innerHTML = «Как ты??»;
Пример
Оповещать HTML-содержимое элемента
с помощью >
Пример
Удалите HTML-содержимое элемента
с помощью >
document.getElementById(«demo»).innerHTML = «»; // Заменяет содержимое
пустой строкой
Пример
Измените HTML-содержимое, URL-адрес и цель ссылки:
document.getElementById(«myAnchor»).innerHTML = «Schoolsw3»;
document.getElementById(«myAnchor»).href = «https://www.schoolsw3.com»;
document.getElementById(«myAnchor»).target = «_blank»;
Упражнения
КАК СДЕЛАТЬ
ПОДЕЛИТЬСЯ
СЕРТИФИКАТЫ
Сообщить об ошибке
Если вы хотите сообщить об ошибке или сделать предложение, не стесняйтесь, присылайте нам электронное письмо:
Ваше предложение:
Спасибо, за вашу помощь!
Ваше сообщение было отправлено в SchoolsW3.
Топ Учебники
Топ Справочники
Топ Примеры
Веб Сертификаты
SchoolsW3 оптимизирован для обучения, тестирования и тренировки. Примеры упрощают и улучшают чтение и базовое понимание.Учебники, справочники, примеры постоянно пересматриваются, для того, чтобы избежать ошибки, невозможно гарантировать правильность всего содержимого.Используя данный сайт, вы соглашаетесь прочитать и принять условия использования, cookie и Политика конфиденциальности.Авторское право 1999 — 2022 Все права защищены.
Работает на W3.CSS.