How to insert adjacent html in Javascript

Insert html element

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.

ValueDescription
afterbeginInserts as the first child of the current element
afterendInserts immediately before the current element
beforebeginInserts immediately before the current element
beforeendInserts as the last child of the current element

Example


<!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> <!--from  w w  w. j a  v a 2 s . c o m-->
<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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window