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

后端 未结 4 1236
深忆病人
深忆病人 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: '▼'; }
    • 1
    • 2
    • 3
    • 4
    • 5

提交回复
热议问题