using javascript's .insertBefore to insert item as last child

Pure JavaScript actually has a method for what you want:

parent.appendChild(child_to_be_last)


The functionality of insertBefore(newNode, referenceNode) is described as:

Inserts the specified node before a reference node as a child of the current node. If referenceNode is null, then newNode is inserted at the end of the list of child nodes.

And since myNodes[i+1] is outside of the array bounds, it returns undefined, which is treated as null in this case. This means you get your desired behavior.

Edit: Link to the W3 specification of insertBefore()


To insert item as a last node use :parentNode.insertBefore(newNode, null);

Tags:

Javascript

Dom