An element's parentNode
property gives you its parent node. Elements have an insertBefore
function that inserts an element before another reference element (moving it if it's already elsewhere in the tree). And nodes have a previousSibling
that gives you the previous sibling node (which may or may not be an element). So:
function swapDiv(elm) {
var previous = findPrevious(elm);
if (previous) {
elm.parentNode.insertBefore(elm, previous);
}
}
...where findPrevious
looks like this:
function findPrevious(elm) {
do {
elm = elm.previousSibling;
} while (elm && elm.nodeType != 1);
return elm;
}
...where your onclick
attributes should be:
onclick="swapDiv(this);"
...although you may want to look into DOM2 event hooking instead (addEventListener
, or attachEvent
on IE).
Slightly OT, but can I recommend using any of the several libraries available that make your life easier, such as Prototype, jQuery, Closure, or any of several others. In fact, there was an error in an earlier version of this because it had been that long since I'd dealt with the DOM directly. :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…