Legal position values are:
"afterbegin"
"afterend"
"beforebegin"
"beforeend"
node.insertAdjacentHTML(position, text)
Parameter | Type | Description |
---|---|---|
position | String | Required. A position relative to the element. Legal values: "afterbegin" - After the beginning of the element (as the first child) "afterend" - After the element "beforebegin" - Before the element "beforeend" - Before the end of the element (as the last child) |
text | String | The text you want to insert |
<h2 id="demo">Am Header</h2> <p>Click the button to insert a paragraph after the header:</p> <button onclick="show_text()">Insert a paragraph</button> <script> function show_text() { var h = document.getElementById("demo1"); h.insertAdjacentHTML("afterend", "<p>Am Paragraph</p>"); } </script>
<h2 id="demo2">Am Second Header</h2> <button class="btn btn-info" onclick="add_span()">Insert a span</button><br><br> <script> function add_span() { var h = document.getElementById("demo2"); h.insertAdjacentHTML("afterbegin", "<span style='color:red'>My span</span>"); } </script>
In above above exampl when you click button it will insert a span inside the header.
Example(3)
<h2 id="demo2">My Header</h2> <button class="btn btn-success" onclick="show_text()">Insert a span</button> <script> function show_text() { var h = document.getElementById("demo2"); h.insertAdjacentHTML("beforebegin", "<span style='color:red'>My span</span>"); } </script>
In above above exampl when you click button it will insert a span before the header.
Complete Code For InsertAdjacentHTML Method In JavaScript
<!DOCTYPE html> <html> <head> <title>Use InsertAdjacentElement Method In Java Script</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <style> h1 { color: mediumvioletred; } </style> <body> <div class="container"> <br> <br> <br> <div class="text-center"> <h1>Use InsertAdjacentElement Method In Java Script</h1> </div> <br> <div class="well"> <h2 id="demo1">Am First Header</h2> <h2 id="demo2">Am Second Header</h2> <h2 id="demo3">Am Second Header</h2> <br><br> <button class="btn btn-primary" onclick="show_text()">Insert a paragraph</button> <button class="btn btn-info" onclick="add_span()">Insert a span</button> <button class="btn btn-info" onclick="add_span_above()">Insert a span</button> </div> </body> </html> <script> function show_text() { var h = document.getElementById("demo1"); h.insertAdjacentHTML("afterend", "<p>Am Paragraph</p>"); } function add_span() { var h = document.getElementById("demo2"); h.insertAdjacentHTML("afterbegin", "<span style='color:red'>My span</span>"); } function add_span_above() { var h = document.getElementById("demo3"); h.insertAdjacentHTML("beforebegin", "<span style='color:deeppink'>My span</span>"); } </script>