Skip to content

JavaScript insertAdjacentHTML() Method

  • by

The insertAdjacentHTML() method is a powerful tool in JavaScript that allows you to dynamically insert HTML content at specific positions relative to an element. It provides flexibility and convenience when it comes to manipulating the content of a web page.

Here’s the syntax for the insertAdjacentHTML() method:

element.insertAdjacentHTML(position, html);

position: A string value that specifies where the HTML should be inserted in relation to the element. It can take one of the following values:

html: A string representing the HTML markup that you want to insert.

const element = document.getElementById('myElement');
element.insertAdjacentHTML('beforeend', '<p>Hello, world!</p>');

With insertAdjacentHTML(), you can choose from four different positions to insert the HTML:

PositionDescription
beforebeginInserts the HTML immediately before the element.
afterbeginInserts the HTML as the first child of the element.
beforeendInserts the HTML as the last child of the element.
afterendInserts the HTML immediately after the element.

JavaScript insertAdjacentHTML() Method example

Simple example code

<!DOCTYPE html>
<html>
<head>
  <title>insertAdjacentHTML() Example</title>
</head>
<body>
  <div id="myElement">Original Content</div>

  <script>
    // Select the element
    const element = document.getElementById('myElement');

    // Insert HTML before the element
    element.insertAdjacentHTML('beforebegin', '<p>Before</p>');

    // Insert HTML as the first child of the element
    element.insertAdjacentHTML('afterbegin', '<p>Inside</p>');

    // Insert HTML as the last child of the element
    element.insertAdjacentHTML('beforeend', '<p>Inside 2</p>');

    // Insert HTML after the element
    element.insertAdjacentHTML('afterend', '<p>After</p>');
  </script>
</body>
</html>

Output:

JavaScript insertAdjacentHTML() Method

This is a basic example, and you can customize the HTML markup and positions according to your specific needs.

Do comment if you have any doubts or suggestions on this JS method code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading