dtsn · I build cool stuff for the web. Hi I'm Daniel and I blog about design, JavaScript and CSS. Find out more about me and subscribe to my feed.

Element.Insert

01/05/2008

Prototype has a very useful function which is not well documented, Element.inset. Element.insert is a very powerful prototype function which lets you insert a element in one of 4 positions, before, after, top, bottom of an element.

If we wanted to insert an element after a element we would use this code:

[code="javascript"]
Element.insert(first-element, {top: content});
[/code]

Expanding this further:

[code="javascript"]
// lets create our element
var dummy = new Element(’div’).update(’Hello World’);
// add the element
Element.insert($(’hook’), {after: dummy});
[/code]
Where hook is the element we want before our created element

This code will add our Hello World text after the div with the id of hook.

One Comment

  • kangax 03/05/2008

    You could also write:

    var dummy = new Element(’div’).update(’Hello World’);
    $(’hook’).insert({ after: dummy });

    or even shorter:

    $(’hook’).insert({ after: new Element(’div’).update(’Hello World’) })

    #insert could also accept object:

    $(’foo’).insert({
    after: ”,
    before: ”,

    })

Reply