views:

4838

answers:

3

I making a website with the javascript library. If the user select a option on a dropdown (select) box there must be added a label and a textbox. This I do with the appendChild option. The only problem with the appenChild option is that the items always be added after the items in used element. This is my code:

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);

Here container is the element where the items must be added. The only problem is that the items are added on the end of the element and I want to added the items on the beginning of the html element.

Thank you,

Ivo Trompert

A: 

Use Insertion.

glavić
A: 
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.

eyelidlessness
+3  A: 

As well as appendChild, DOM nodes have an insertBefore method

container.insertBefore(newFreeformLabel, container.firstChild);
Gareth