Can I insert elements to the beginning of an element using .appendChild()?

Ivo Trompert picture Ivo Trompert · Mar 6, 2009 · Viewed 85.9k times · Source

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?

Answer

Gareth picture Gareth · Mar 6, 2009

As well as appendChild, DOM nodes have an insertBefore method

container.insertBefore(newFreeformLabel, container.firstChild);