Legal position values are:
"afterbegin"
"afterend"
"beforebegin"
"beforeend"
node.insertAdjacentElement(position, element)
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) |
element | HTML Element | The element you want to insert |
Example(1)
<span style="color:red">am span</span> <h2 id="demo1">Am First Header</h2> <button class="btn btn-success" onclick="show_words()">Move span</button> <script> function show_words() { var s = document.getElementsByTagName("span")[0]; var h = document.getElementById("demo"); h.insertAdjacentElement("afterend", s); } </script>
<span style="color:red">My span</span> <h2 id="demo">My Header</h2> <button onclick="show_text()">Move span</button> <script> function show_text() { var s = document.getElementsByTagName("span")[0]; var h = document.getElementById("demo"); h.insertAdjacentElement("afterbegin", s); } </script>
<!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"> <div class="text-center"> <h1>Use InsertAdjacentElement Method In Java Script</h1> </div> <br> <div class="well"> <span style="color:red">My span</span> <h2 id="demo1">Am First Header</h2> <h2 id="demo2">Am Second Header</h2> <br><br> <button class="btn btn-primary" onclick="change_pos()">changes text position</button><br><br> <button class="btn btn-info" onclick="myFunction()">Move span</button> </div> </body> </html> <script> function change_pos() { var s = document.getElementsByTagName("span")[0]; var h = document.getElementById("demo1"); h.insertAdjacentElement("afterend", s); } function myFunction() { var s = document.getElementsByTagName("span")[0]; var h = document.getElementById("demo2"); h.insertAdjacentElement("afterbegin", s); } </script>