Question

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.

Was it helpful?

Solution

As well as appendChild, DOM nodes have an insertBefore method

container.insertBefore(newFreeformLabel, container.firstChild);

OTHER TIPS

container.prepend(newChild);

This was added in ES5. It is vanilla JS and currently available in 90% of browsers, including Chrome, FF, and Opera.

In addition, newFreeformLabel.after(newFreeformField); would allow you to insert in order, if desired. .before is also an option

Links: developer.mozilla.org - Polyfill

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.

If I had seen Gareth's solution on time, I might go with that, as it was I used:

$('toggle_product').innerHTML = insertContent + $('toggle_product').innerHTML;

as Prototypes' insert() function was returning error in IE8..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top