The insertAdjacentElement()
method inserts a an
element into a specified position.
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) |
element.insertAdjacentElement(position, element)
or
node.insertAdjacentElement(position, element)
Parameter | Description |
position |
Required. A position relative to the element: afterbegin afterend beforebegin beforeend |
element | The element to insert. |
The insertAdjacentHTML()
method inserts HTML code
into a specified position.
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) |
element.insertAdjacentHTML(position, html)
or
node.insertAdjacentHTML(position, html)
Parameter | Description |
position |
Required. A position relative to the element: afterbegin afterend beforebegin beforeend |
html | The HTML to insert. |
<!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>
// 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);