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

container.
    insert({
        // key is position
        // 'before', 'after', 'top' and 'bottom' are allowed
        top: new Element('label').
            update('Omschrijving:')
    }).
    insert({
        top: new Element('input').
            addClassName('textfield').
            writeAttribute('name', 'factuur_orderregel[]')
    }).
    insert({
        top: new Element('div').
            addClassName('spacer')
    });

I think Prototype's Element.insert is somewhat awkward for before/after, however. For instance, if you wanted to place the .spacer before the .textfield, sometime later in your code, you would need to do something like:

container.
    down('.textfield').
    insert({
        before: new Element('div').
            addClassName('spacer')
    });

This is, especially if you're familiar with the DOM API's Element.insertBefore, somewhat unintuitive, as you are not inserting the .spacer into the .textfield, but instead into the container, before the .textfield.


Use Element.insert(element, content).


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

  1. You can pass multiple values (or use spread operator ...).
  2. 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


As well as appendChild, DOM nodes have an insertBefore method

container.insertBefore(newFreeformLabel, container.firstChild);