Can I insert elements to the beginning of an element using .appendChild()?
If the user selects an option in a dropdown box, there must be added a label and a textbox. Using appendChild
, these elements get added to the end of the container
.
var newFreeformLabel = document.createElement('label');
newFreeformLabel.innerHTML = 'Omschrijving:';
var newFreeformField = document.createElement('input');
newFreeformField.className = 'textfield';
newFreeformField.name = 'factuur_orderregel[]';
var newFreeformSpacer = document.createElement('div');
newFreeformSpacer.className = 'spacer';
container.appendChild(newFreeformLabel);
container.appendChild(newFreeformField);
container.appendChild(newFreeformSpacer);
The issue is that these elements should be inserted at the beginning of container
, not at the end.
Is there a solution to this in PrototypeJS?
Solution 1:
As well as appendChild
, DOM nodes have an insertBefore method
container.insertBefore(newFreeformLabel, container.firstChild);
Solution 2:
Modern Solution
To add a child to the beginning of a parent, use prepend
parent.prepend(newChild)
To add at the end of a parent, use append
parent.append(newChild)
In addition, if you want to add relative to another child, use one of these:
child1.after(newChild) // [child1, newChild, child2]
child1.before(newChild) // [newChild, child1, child2]
Advanced usage
- You can pass multiple values (or use spread operator
...
). - Any string value will be added as a text element.
Examples:
parent.prepend(newChild, "foo") // [newChild, "foo", child1, child2]
const list = ["bar", newChild]
parent.append(...list, "fizz") // [child1, child2, "bar", newChild, "fizz"]
Related DOM method - child.replaceWith
Documentation
Can I Use
Solution 3:
Use Element.insert(element, content)
.