Creating DOM Elements...and Other Related Stuff!

by kirupa | 28 January 2014

This part may blow you away. For the following sentences, I suggest you hold onto something sturdy:


This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/creating_dom_elements_and_other_stuff.htm

Handy Dandy Function… example has error. (2nd edition, page 313):
Below is an example of this function at work:

let newElement = document.createElement("p");
let bodyElement = document.querySelector("body");
let h1Element = document.querySelector("h1");

newElement.textContent = "I exist entirely in your imagination.";

function insertAfter(target, element) {
  target.parentNode.insertBefore(element, target.nextSibling);
}

insertAfter(bodyElement, newElement);

Using bodyElement as the first argument, target.parentNode is html.
If you want to put the <p> after the h1, you need to use h1Element as first argument (ie, target).
Then it works but…stepping thru the code with Chrome Developer shows that target.nextSibling = text just before the <p> element is inserted. Still <p> is inserted as desired after h1.
Comments appreciated.

Charles

Hey Charles - you are totally right. There is a bug in my example. The problem is with target.parentNode. The following code with parentNode removed works properly…at least for this example:

let newElement = document.createElement("p");
let bodyElement = document.querySelector("body");
let h1Element = document.querySelector("h1");

newElement.textContent = "I exist entirely in your imagination.";

insertAfter(bodyElement, newElement);

function insertAfter(target, element) {
  target.insertBefore(element, target.nextSibling);
}