snippetjavascriptTip
Insert HTML string before or after element using JavaScript
Viewed 0 times
javascriptinsertafterelementbeforeusinghtmlstring
Problem
JavaScript's
The position that corresponds to inserting an HTML string before the start of a specified element is
Similarly, to insert an HTML string after the start of a specified element, you can use
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.Similarly, to insert an HTML string after the start of a specified element, you can use
Element.insertAdjacentHTML() with a position of 'afterend'.Solution
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'.Code Snippets
const insertBefore = (el, htmlString) =>
el.insertAdjacentHTML('beforebegin', htmlString);
insertBefore(document.getElementById('myId'), '<p>before</p>');
// <p>before</p> <div id="myId">...</div>const insertAfter = (el, htmlString) =>
el.insertAdjacentHTML('afterend', htmlString);
insertAfter(document.getElementById('myId'), '<p>after</p>');
// <div id="myId">...</div> <p>after</p>Context
From 30-seconds-of-code: insert-html-string-before-or-after-element
Revisions (0)
No revisions yet.