insertAdjacentHTML
insertAdjacentHTML method takes two arguments.
The second is the fragment to insert.
The first is a value from the following table indicating where the fragment should be inserted relative to the current element.
Value | Description |
---|---|
afterbegin | Inserts as the first child of the current element |
afterend | Inserts immediately before the current element |
beforebegin | Inserts immediately before the current element |
beforeend | Inserts as the last child of the current element |
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<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>
Home
JavaScript Book
DOM
JavaScript Book
DOM
HTMLElement:
- The HTMLElement Members
- element tag name, id, direction, language, hidden disabled information
- addEventListener
- appendChild
- attributes returns a collection containing all of the attributes
- classList
- className
- cloneNode
- createElement
- createTextNode
- dataset
- getAttribute
- getElementsByTagName
- hasAttribute
- innerHTML
- insertAdjacentHTML
- insertBefore
- isSameNode
- outerHTML
- onmouseout
- onmouseover
- querySelectorAll
- removeEventListener