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);
}

For the Handy Dandy Function to make sense to the people who are reading it shouldn’t it really be insertAfter(h1Element, newElement); ? Technically there is nothing wrong with you using bodyElement but wouldn’t it be become a ‘sibling’ of bodyElement and throughout the whole example we have been demonstrating how to insert the newElement within the boundaries of the children of the bodyElement. Also it is a bit confusing within the website example above as the original function has the parentnode property and then when you provide an example , the parentnode property is remitted from the same function

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

and then

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

ps: there is a minor clerical error on the clone item code within the website version.

bodyElement.appenChild(clonedItem);
```.

You are correct on all counts here. Reading what I wrote gives me a headache. Thanks for pointing it out. I will get that section revised shortly. The snippet needs to have parentNode called out, so the code in the second part of what I wrote is wrong.

Edit: I revised that section.