Insert to adjacent html with afterend in JavaScript

Description

The following code shows how to insert to adjacent html with afterend.

Example


<!--   ww w  . j  a  v  a2 s  . com-->
<!DOCTYPE HTML>
<html>
<body>
<table border="1">
<thead><tr><th>A</th><th>B</th></tr></thead>
<tbody>
<tr id="myRow"><td>Placeholder</td></tr>
</tbody>
</table>
<button id="ab">After Begin</button>
<button id="ae">After End</button>
<button id="bb">Before Begin</button>
<button id="be">Before End</button>
<script>
var target = document.getElementById("myRow");
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
if (e.target.id == "ab") {
target.insertAdjacentHTML("afterbegin", "<td>After Begin</td>");
} else if (e.target.id == "be") {
target.insertAdjacentHTML("beforeend", "<td>Before End</td>");
} else if (e.target.id == "bb") {
target.insertAdjacentHTML("beforebegin", "<tr><td colspan='3'>Before Begin</td></tr>");
} else {
target.insertAdjacentHTML("afterend","<tr><td colspan='2'>After End</td></tr>");
}
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Insert to adjacent html with afterend in JavaScript
Home »
  Javascript Tutorial »
    DOM »
      Insert
Javascript Tutorial Insert
Add child to a HTML element in JavaScript
Insert a node before another element using ...
Insert as the new first child in JavaScript
Insert before last child in JavaScript
Insert element before another element in Ja...
Insert to adjacent html with afterbegin in ...
Insert to adjacent html with afterend in Ja...
Insert to adjacent html with beforebegin in...
Insert to adjacent html with beforeend in J...