使用javascript在dom树中将元素向上或向下移动一个位置 [英] Move an element one place up or down in the dom tree with javascript

查看:715
本文介绍了使用javascript在dom树中将元素向上或向下移动一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用JavaScript的方式使用javascript(或jquery可以)在特定已知父级的dom树中将元素在dom树中上移或下移,但是我希望脚本知道元素是第一个还是最后一个元素在父元素之内并且不被移动.例如,如果我有以下...

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 know when an element is the first or last element within the parent and not be moved. for example, if i have the following ...

<div id='parent_div'>
    <div id='div_1'></div>
    <div id='div_2'></div>
    <div id='div_3'></div>
</div>

在单击按钮时,我想传递一个已知的id(比方说div_2)并将其向上移动到其上方的位置,将其位置与之前的元素交换(在本例中为).元素的id不必更改,并且不需要知道它们的新位置,至少除非再次移动它们,否则就不必知道.

on click of a button, i want to pass a known id (let's say div_2) and move it up to the position above it, swapping its position with the element that was previously before it (in this case div_1). The ids of the elements don't have to change, and their new position doesn't need to be known, at least not unless they are moved again.

推荐答案

使用jQuery:

var e = $("#div_2");
// move up:
e.prev().insertAfter(e);
// move down:
e.next().insertBefore(e);

这篇关于使用javascript在dom树中将元素向上或向下移动一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆