Prototype’s Element.insert
So today I was working on a small item that I figured would be pretty straight forward…until I went to Prototype’s documentation. I want to say that overall, I really like Prototype’s doc site. Overall, it is laid out well and 95% of the time has exactly what I need. Unfortunately, this is one time where it didn’t. I wanted to implement a simple select box with two arrow buttons next to it (up and down). The goal was to allow users to order the options in the select box. Below is the code I was using for moving an element up (down was similar):
function upOption() {
if(!clicked) {
clicked = true;
options = $('selectId').childElements();
for(var i = 0; i < options.length;) {
element = options[i];
if(element.selected && (i - 1) >= 0 ) {
options[i].remove();
options.splice(i, 1);
Element.insert(options[i - 1], {before: element});
}
i++;
}
clicked = false;
}
};
Where I got stuck was on the Element.insert. The documentation (as found here) states that “Inserts content before, after, at the top of, or at the bottom of element, as specified by the position property of the second argument. If the second argument is the content itself, insert will append it to element.”. What does that mean?!?!
I’ll tell you what it means. Element.insert takes two parameters, the element to insert the new content ajacent to and one of the following:
- The content to be inserted
- A Hash with a single key that dictates where to put the content with the content as the value
The example above is an example of the option with the hash. What this does is it takes options[i - 1] and places element into the DOM as the first sibling above options[i - 1]. What each option does is as follows:
- before: Places the element as the first sibling before the identified element in the DOM
- after: Places the element as the first sibling after the identified element in the DOM
- top: Places the element as the first child under the identified element in the DOM
- bottom: Places the element as the last child under the identified element in the DOM
If we use the example Element.insert($('myList'), {XXX: new Element('p')});, the new p element would show up in the corresponding place:
<div id="container">
before
<ul id=”myList”>
top
<li>element 1</li>
<li>element 2</li>
<li>element 3</li>
bottom
</ul>
after
</div>
So there you have it. Please feel free to point out any optimizations I could do in my method. One I already know about but was unable to get working was removing the line element = options[i]; and just use the element returned from the remove() function. Unfortunately, I was unable to get that to work (as tested in IE7). As always, I look forward to the comments!

Blog 
