How to swap 2 Divs in a Container with Javascript

Posted in :

有二個div 區塊內容想互換, 透過 javascript 的解法:

解法1, innerHTML, 這個方法較弱, 不建議使用, 因為遇到 node 有 id 或其他屬性就麻煩了.

let div1 = document.querySelector(".div1");
let div4 = document.querySelector(".div4");
let temp = div1.cloneNode(true);

div1.innerHTML = div4.innerHTML;
div1.className = div4.className;

div4.innerHTML = temp.innerHTML;
div4.className = temp.className;
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>

解法2

it’s simple, first you need to container all the div you need to make this script like this, we will write the function later you can try it by the link https://codepen.io/nt0412/pen/rNJWMKP

<div class="all-div-container">
   <div class="div1" onclick="swapDiv(event,this);">
         1
   </div>
   <div class="div2" onclick="swapDiv(event,this);">
         2
   </div>
   <div class="div3" onclick="swapDiv(event,this);">
         3
   </div>
   <div class="div4" onclick="swapDiv(event,this);">
         4
   </div>
   <div class="div5" onclick="swapDiv(event,this);">
         5
   </div>
</div>
<script type="text/javascript">
    function swapDiv(event, elem) {
        elem.parentNode.insertBefore(elem, elem.parentNode.firstChild);
    }
</script>

資料來源:
https://stackoverflow.com/questions/67881886/how-to-swap-2-divs-in-a-container-with-javascript


解法3:
https://stackoverflow.com/questions/2943140/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 PrototypejQuery, 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. 🙂


相關文章

[JS] 深入淺出 JavaScript 閉包(closure)
https://pjchender.dev/javascript/js-closure/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *