JavaScript – Insert Element After Specific Div Element - Tutorial Kart
Maybe your like
JavaScript – Insert Element after Specific Div Element
To insert element in document after div element using JavaScript, get reference to the div element; call after() method on this div element; and pass the element to insert, as argument to after() method.
Examples
In the following example, we have div with id "myDiv", and we shall add a paragraph element after this div using after() method.
HTML File
</> Copy <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> #myDiv { width:100px; height:100px; background:rgb(67, 187, 12); } </style> </head> <body> <h2>Append HTML after Div using JavaScript</h2> <div id="myDiv"></div> <br> <button type="button" onclick="execute()">Click Me</button> <script> function execute(){ var para = document.createElement('p'); para.textContent = 'Hello World!'; var element = document.getElementById('myDiv'); element.after(para); } </script> </body> </html>Example 2 – Insert Div in Document after Specific Div
Now, let us create a div element and insert this div after the element with id "myDiv" using after() method.
HTML File
</> Copy <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> div { width:100px; height:100px; margin:10px; background:rgb(67, 187, 12); } </style> </head> <body> <h2>Append HTML after Div using JavaScript</h2> <div id="myDiv"></div> <br> <button type="button" onclick="execute()">Click Me</button> <script> function execute(){ var anotherDiv = document.createElement('div'); var element = document.getElementById('myDiv'); element.after(anotherDiv); } </script> </body> </html>When you click on Click Me button in the output of HTML, a new div will be added after the div element with id "myDiv".
Conclusion
In this JavaScript Tutorial, we learned how to insert an element in the document after a div using JavaScript.
Tag » Add Div On Click Javascript
-
Add Click Event On Div Tag Using JavaScript - Html - Stack Overflow
-
Create An Element With OnClick Event Listener Using JS | Bobbyhadz
-
How To Add A Class Name - W3Schools
-
HTML DOM Document CreateElement() Method - W3Schools
-
JQuery Append() Method - W3Schools
-
HTML DOM Element Click() Method - W3Schools
-
How To Append HTML Code To A Div Using JavaScript - GeeksforGeeks
-
How To Add A Number To A Div After Clicking A Button In JavaScript
-
How To Add A Click Event Listener On Div Tag Using JavaScript?
-
Onclick Append Class To Div In Javascript Code Example
-
How To Append Or Add Text To A DIV Element Using JavaScript
-
Add New Div While Click A Button Using Javascript Or Jquery
-
Javascript Add Button To Div Code Example
-
HTML Button Onclick – JavaScript Click Event Tutorial