Javascript DOM Element Insert Before
<!DOCTYPE html> <head> <script> window.onload=function() {//from w ww . j av a2s . c om let para = document.getElementsByTagName("p"); let parent = para[0].parentNode; parent.insertBefore(para[para.length-1], para[0]); } </script> </head> <body> <div id="target"> <p>This is the first paragraph</p> <p>This is the second paragraph</p> <p>This is the third paragraph</p> <p>This is the fourth paragraph</p> </div> </body> </html>
<!DOCTYPE html> <head> <title>Recipe</title> <script> window.onload=function() {/*from w w w . j a va 2 s. c om*/ // get the existing element let refElement = document.getElementById("sister"); // get the element's parent node let parent = refElement.parentNode; // create new div element let newDiv = document.createElement("div"); // attach to page before sister element parent.insertBefore(newDiv, refElement); // give it some content newDiv.innerHTML = "<p>This is the new div element</p>"; } </script> </head> <body> <div id="sister"><p>This is the old content</p></div> </body> </html>