如何在树中将元素向上/向下移动一个位置

7

我似乎找不到JavaScript的一个基本功能。我想通过按钮单击将一个元素向上或向下移动一个位置。jQuery和其他专有库不是选择。

function moveDown()
{
    if (document.getElementById('CMSeditingNode'))
    {
        var node = document.getElementById('CMSeditingNode'),
        parent = node.parentNode,
        nextNode = node.nextSibling,
        secondNode = nextNode.nextSibling,
        oldChild = parent.removeChild(node);
        parent.insertBefore(oldChild, secondNode);
    }
}

答案完美地解决了我的问题,我在这篇帖子中补充了insertAfter()的内容。

1
你尝试过什么?你研究过什么?出了什么问题?你使用的是哪种标记语言? - David Thomas
我根据我的问题和几个变化进行了搜索。我尝试使用contenteditable > grab by id > create new with outerHTML,然后删除旧的div。正如您所看到的描述一样,这相当复杂。需要什么标记?HTML。 - Richard
1个回答

20

你需要的方法/属性是 parentNodepreviousSiblingnextSiblingremoveChildinsertBeforeinsertAdjacentElement。代码示例如下:

var node = document.getElementById('somenode'),
    parent = node.parentNode,
    prev = node.previousSibling,
    oldChild = parent.removeChild(node);
parent.insertBefore( oldChild, prev );

仅供比较,这个完整的 jQuery 代码如下:

var $node = $('#somenode'),
            $node.prev().before($node);

非常感谢您的回复。我会开始使用它。 - Richard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接