title | shortTitle | type | language | tags | cover | excerpt | dateModified | |
---|---|---|---|---|---|---|---|---|
Insert HTML string before or after element using JavaScript |
Insert HTML string before or after element |
story |
javascript |
|
malibu |
Learn how to insert an HTML string before or after the start of a specified element using JavaScript. |
2024-01-29 |
JavaScript's Element.insertAdjacentHTML()
method allows you to insert an HTML string at various positions relative to a specified element. One of the most common use-cases is to insert an HTML string before or after the start of a specified element.
The position that corresponds to inserting an HTML string before the start of a specified element is 'beforebegin'
. You can use Element.insertAdjacentHTML()
with this position to insert a given HTML string before the start of the specified element.
const insertBefore = (el, htmlString) =>
el.insertAdjacentHTML('beforebegin', htmlString);
insertBefore(document.getElementById('myId'), '<p>before</p>');
// <p>before</p> <div id="myId">...</div>
Similarly, to insert an HTML string after the start of a specified element, you can use Element.insertAdjacentHTML()
with a position of 'afterend'
.
const insertAfter = (el, htmlString) =>
el.insertAdjacentHTML('afterend', htmlString);
insertAfter(document.getElementById('myId'), '<p>after</p>');
// <div id="myId">...</div> <p>after</p>