Move an element one place up or down in the dom tree with javascript

后端 未结 4 1229
深忆病人
深忆病人 2021-01-31 03:15

I want a javascript way to move an element one place up or down in the dom tree within a particular known parent using javascript (or jquery is ok), but i want the script to kno

相关标签:
4条回答
  • 2021-01-31 03:36

    Move element "up":

    if(element.previousElementSibling)
      element.parentNode.insertBefore(element, element.previousElementSibling);
    

    Move element "down":

    if(element.nextElementSibling)
      element.parentNode.insertBefore(element.nextElementSibling, element);
    

    function moveUp(element) {
      if(element.previousElementSibling)
        element.parentNode.insertBefore(element, element.previousElementSibling);
    }
    function moveDown(element) {
      if(element.nextElementSibling)
        element.parentNode.insertBefore(element.nextElementSibling, element);
    }
    document.querySelector('ul').addEventListener('click', function(e) {
      if(e.target.className === 'down') moveDown(e.target.parentNode);
      else if(e.target.className === 'up') moveUp(e.target.parentNode);
    });
    .up, .down        { cursor: pointer; }
    .up:after         { content: '△'; }
    .up:hover:after   { content: '▲'; }
    .down:after       { content: '▽'; }
    .down:hover:after { content: '▼'; }
    <ul>
      <li>1<span class="up"></span><span class="down"></span></li>
      <li>2<span class="up"></span><span class="down"></span></li>
      <li>3<span class="up"></span><span class="down"></span></li>
      <li>4<span class="up"></span><span class="down"></span></li>
      <li>5<span class="up"></span><span class="down"></span></li>
    </ul>

    0 讨论(0)
  • 2021-01-31 03:40

    With jQuery:

    var e = $("#div_2");
    // move up:
    e.prev().insertAfter(e);
    // move down:
    e.next().insertBefore(e);
    
    0 讨论(0)
  • 2021-01-31 03:53

    You can use JQuery's built in .index() method to get the location of a child element and get the .length value form a parent element to find out the number of elements.

    If index comes back 0, it is the first element, if the index comes back parent element length -1 then you know it is the last element.

    For moving the elements them self you can use .insertBefore and .prev to move an element up.

        var elm = $("selector_for_the_element");
        elm.insertBefore(elm.prev());
    

    For moving an elemetn down then you can use insertAfter and .next

        var elm = $("selector_for_the_element");
        elm.insertAfter(elm.next());
    
    0 讨论(0)
  • 2021-01-31 03:55

    Get all the child div with parent div id (#parent_div) using $.each function of jQuery. suppose you want to swap div3 with div2, then index of div3 will be 2. use $(#div_3).insertBefore(#div_2)

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