JavaScript moving element in the DOM

后端 未结 7 1566
囚心锁ツ
囚心锁ツ 2020-11-27 12:25

Let\'s say I have three

elements on a page. How can I swap positions of the first and third
? jQuery is fine.

相关标签:
7条回答
  • 2020-11-27 13:02

    There's no need to use a library for such a trivial task:

    var divs = document.getElementsByTagName("div");   // order: first, second, third
    divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second
    divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, first
    

    This takes account of the fact that getElementsByTagName returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.

    You could also use:

    var divs = document.getElementsByTagName("div");   // order: first, second, third
    divs[0].parentNode.appendChild(divs[0]);           // order: second, third, first
    divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, first
    

    and there are various other possible permutations, if you feel like experimenting:

    divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));
    

    for example :-)

    0 讨论(0)
提交回复
热议问题