How to swap HTML elements in javascript?
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. :-)
This code will do what you want (if you want to swap the selected with the first child element). In case you want something else you need to be more precise.
<script type="text/javascript">
function swapDiv(event, elem) {
elem.parentNode.insertBefore(elem, elem.parentNode.firstChild);
}
</script>
<div id="container">
<div onclick="swapDiv(event,this);">1</div>
<div onclick="swapDiv(event,this);">2</div>
<div onclick="swapDiv(event,this);">3</div>
</div>