document.body.insertAdjacentElement("afterbegin",
new DOMParser().parseFromString("<div> Hello </div>", "text/html").documentElement);
1
2
3
4
5
6
7
8
9
10
11
12
13
let element = document.getElementById('node');
// Vị trí 1: beforebegin
element.insertAdjacentHTML("beforebegin", '<span>Nội dung chèn 1</span>');
// Vị trí 2: afterbegin
element.insertAdjacentHTML("afterbegin", '<span>Nội dung chèn 2</span>');
// Vị trí 3: beforeend
element.insertAdjacentHTML("beforeend", '<span>Nội dung chèn 3</span>');
// Vị trí 4: afterend
element.insertAdjacentHTML("afterend", '<span>Nội dung chèn 4</span>');
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM insertAdjacentElement() Method</h1>
<p>This method inserts a specified element, into a specified position.</p>
<span style="color:red">My span</span>
<h2 id="myH2">My Header</h2>
<p>Click the button to insert the red span after the header:</p>
<button onclick="myFunction()">Move span</button>
<script>
function myFunction() {
var s = document.getElementsByTagName("span")[0];
var h = document.getElementById("myH2");
h.insertAdjacentElement("afterend", s);
}
</script>
</body>
</html>