JS insert


insertAdjacentElement()

The insertAdjacentElement() method inserts a an element into a specified position.

Legal positions:

Value

Description

afterbegin

After the beginning of the element (first child)

afterend

After the element

beforebegin

Before the element

beforeend

Before the end of the element (last child)

Syntax

element.insertAdjacentElement(position, element)
                  or
node.insertAdjacentElement(position, element)

Parameters

Parameter Description
position Required.
A position relative to the element:
afterbegin
afterend
beforebegin
beforeend
element The element to insert.

insertAdjacentHTML()

The insertAdjacentHTML() method inserts HTML code into a specified position.

Legal positions:

Value Description
afterbegin After the beginning of the element (first child)
afterend After the element
beforebegin Before the element
beforeend Before the end of the element (last child)

Syntax

element.insertAdjacentHTML(position, html)
                or
node.insertAdjacentHTML(position, html)

Parameters

Parameter Description
position Required.
A position relative to the element:
afterbegin
afterend
beforebegin
beforeend
html The HTML to insert.

html file

<!DOCTYPE html>
<html>
<head>
    <title>DOM Navigation</title>
    <style>
        #test{
            background: #ffff00;
            width: 800px;
            height: 200px;
            padding: 10px 10px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div id="test">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur aperiam eos vel consequatur. Delectus voluptas
            dolorem id exercitationem, ad ipsam consectetur hic ullam provident! Adipisci exercitationem ipsam rerum sunt
            doloremque magni soluta, delectus maiores, sapiente quasi labore praesentium accusamus earum cum nam saepe qui?
            Accusamus provident quo perferendis sint sed.</p>
    </div>
    <script src="js/dom-create.js"></script>
</body>
</html>

dom-create.js

//  insertAdjacentElement Method

var newElement = document.createElement("h2");

var newText = document.createTextNode("This is just element");

newElement.appendChild(newText);

var target = document.getElementById("test");

target.insertAdjacentElement("afterbegin",newElement);


//  insertAdjacentHTML Method

var newElement = "<h2>This is just Html</h2>";

var target = document.getElementById("test");

target.insertAdjacentHTML("afterend",newElement);

//  insertAdjacentText Method

var newText = "<h2>This is just Text</h2>";

var target = document.getElementById("test");

target.insertAdjacentHTML("beforeend",newText);