Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

dom - How to swap HTML elements in javascript?

I am using classic Javascript for DOM scripting, i have a set of DIV's in a container DIV. On click event of child DIV's, i want that the child DIV which has caused event to be swaped with the DIV above it.. my code goes here..

 <div id="container">
        <div onclick="swapDiv(event);">1</div>
        <div onclick="swapDiv(event);">2</div>
        <div onclick="swapDiv(event);">3</div>
 </div>

if DIV 2 has been clicked it should be swap with DIV 1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...