Legal position values are:
"afterbegin"
"afterend"
"beforebegin"
"beforeend"
Syntax and Usage
node.insertAdjacentText(position, text)
Parameter Values
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 |
Example(1)
<h2 id="demo">My Header</h2> <p>Click the button to insert some text after the header:</p> <button onclick="after_header()">Insert text after header</button> <script> function after_header() { var h = document.getElementById("demo"); h.insertAdjacentText("afterend", "My inserted text"); } </script>
In above example when you click the button it will insert some text after the header
Example(2)<h2 id="demo">My Header</h2> <button class="btn btn-success" onclick="insert_middle()">Insert text</button> <script> function myFunction() { var h = document.getElementById("demo"); h.insertAdjacentText("afterbegin", "My inserted text"); } </script>
<!DOCTYPE html> <html> <head> <title>Use InsertAdjacentText 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 InsertAdjacentText 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 third Header</h2> <h2 id="demo4">Am fourth Header</h2> <br><br> <button class="btn btn-primary" onclick="after_span()">Insert a paragraph</button> <button class="btn btn-info" onclick="add_span_middle()">Insert a span</button> <button class="btn btn-info" onclick="add_span_above()">Insert a span</button> <button class="btn btn-info" onclick="add_span_below()">Insert a span</button> </div> </body> </html> <script> function after_span() { var h = document.getElementById("demo1"); h.insertAdjacentText("afterend", "My inserted text");//example 1 } function add_span_middle() { var h = document.getElementById("demo2"); h.insertAdjacentText("afterbegin", "My inserted text");// example 2 } function add_span_above() { var h = document.getElementById("demo3"); h.insertAdjacentText("beforebegin", "My inserted text");//example 3 } function add_span_below() { var h = document.getElementById("demo4"); h.insertAdjacentText("afterend", "My inserted text");//example 4 } </script>