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.

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
 
<!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>
  
Click to view the demo
Home 
  JavaScript Book 
    DOM  

HTMLElement:
  1. The HTMLElement Members
  2. element tag name, id, direction, language, hidden disabled information
  3. addEventListener
  4. appendChild
  5. attributes returns a collection containing all of the attributes
  6. classList
  7. className
  8. cloneNode
  9. createElement
  10. createTextNode
  11. dataset
  12. getAttribute
  13. getElementsByTagName
  14. hasAttribute
  15. innerHTML
  16. insertAdjacentHTML
  17. insertBefore
  18. isSameNode
  19. outerHTML
  20. onmouseout
  21. onmouseover
  22. querySelectorAll
  23. removeEventListener