Insert to adjacent html with beforeend in JavaScript
Description
The following code shows how to insert to adjacent html with beforeend.
Example
<!--from w ww . ja v a2 s . c o m-->
<!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>
The code above generates the following result.
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...
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...