I so miss jQuery. I\'m working on a project where I need to get my hands dirty with good \'ol plain Javascript again.
I have this scenario:
parent
If you want to position based on child, simply use before
or after
child1.before(newNode) // [newNode, child1, child2]
// or
child1.after(newNode) // [child1, newNode, child2]
If you want to position based on parent, use prepend
or append
parent.prepend(newNode) // [newNode, child1, child2]
// or
parent.append(newNode) // [child1, child2, newNode]
...
).Examples:
child1.after(newNode, "foo") // [child1, newNode, "foo", child2]
const list = ["bar", newNode]
parent.prepend(...list, "fizz") // ["bar", newNode, "fizz", child1, child2]
before - after
prepend - append
Can I Use - 93% Aug 2020
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, thennewNode
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()
I got this code is work to insert a link item as the last child
var cb=function(){
//create newnode
var link=document.createElement('link');
link.rel='stylesheet';link.type='text/css';link.href='css/style.css';
//insert after the lastnode
var nodes=document.getElementsByTagName('link'); //existing nodes
var lastnode=document.getElementsByTagName('link')[nodes.length-1];
lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
};
var raf=requestAnimationFrame||mozRequestAnimationFrame||
webkitRequestAnimationFrame||msRequestAnimationFrame;
if (raf)raf(cb);else window.addEventListener('load',cb);
To insert item as a last node use :parentNode.insertBefore(newNode, null);
Also when not iterating through children (just inserting after referenceNode
) this might be useful:
parentNode.insertBefore(newNode, referenceNode.nextSibling);