Element: insertAdjacentHTML() method
The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
Syntax
Parameters
A string representing the position relative to the element. Must be one of the following strings:
Before the element. Only valid if the element is in the DOM tree and has a parent element.
Just inside the element, before its first child.
Just inside the element, after its last child.
After the element. Only valid if the element is in the DOM tree and has a parent element.
The string to be parsed as HTML or XML and inserted into the tree.
Return value
Exceptions
This method may raise a DOMException of one of the following types:
Thrown if position is «beforebegin» or «afterend» and the element either does not have a parent or its parent is the Document object.
Thrown if position is not one of the four listed values.
Description
The insertAdjacentHTML() method does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.
We can visualize the possible positions for the inserted content as follows:
Security considerations
When inserting HTML into a page by using insertAdjacentHTML() , be careful not to use user input that hasn’t been escaped.
Как в javascript вставить html

WordPress 6 с Нуля до Гуру
Этот курс научит Вас созданию самых разных сайтов на самой популярной в мире CMS — WordPress. Вы увидите установку и настройку локального сервера, разбор каждой настройки, каждой кнопки и каждого пункта меню в панели WordPress.
Также Вы получите и всю практику, поскольку прямо в курсе с нуля создаётся полноценный Интернет-магазин, который затем публикуется в Интернете. И всё это прямо на Ваших глазах.
Помимо уроков к курсу идут упражнения для закрепления материала.
И, наконец, к курсу идёт ценнейший Бонус по тому, как используя ChatGPT и создавая контент для сайта, можно выйти на пассивный доход. Вы наглядно увидите, как зарегистрироваться в ChatGPT (в том числе, и если Вы из России), как правильно выбрать тему для сайта, как правильно генерировать статьи для него(чтобы они индексировались поисковыми системами) и как правильно монетизировать трафик на сайте.
Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.
Подписаться

Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.
Подписаться

Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.
Метод insertAdjacentHTML
Метод insertAdjacentHTML позволяет вставить строку HTML кода в любое место страницы. Код вставляется относительно опорного элемента. Можно сделать вставку перед опорным элементом (способ вставки ‘beforeBegin’ ), после него (способ вставки ‘afterEnd’ ), а также в начало (способ вставки ‘afterBegin’ ) или в конец (способ вставки ‘beforeEnd’ ) опорного элемента.
Синтаксис
Пример . Способ beforeBegin
Пусть опорный элемент — это элемент #target . Вставим перед ним новый абзац:
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 <p> element:
Example
- The HTML document above contains a <p> 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 <h1> element:
Example
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
- The HTML document above contains an <h1> 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 <img> element:
Example
- The HTML document above contains an <img> 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
<script>
document.getElementById(«demo»).innerHTML = «Date : » + Date(); </script>
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.