在JavaScript中将孩子从一个父母移动到另一个父母?

时间:2017-11-08 22:23:55

标签: javascript jquery html parent-child

我希望能够更改父元素。基本上我想将一个元素从一个父元素移动到另一个父元素。我希望在Javascript中实现这一点,最好只使用JQuery库。

在代码之前:

<div id = "div1">
  <p id = "paragraph">
    Lorem ipsum dolor sit amet, adipiscing pellentesque egestas.
  </p>
</div> 
<div id = "div2></div>

代码后:

<div id = "div1"> </div> 
<div id = "div2>
  <p id = "paragraph">
    Lorem ipsum dolor sit amet, adipiscing pellentesque egestas.
  </p>
</div>

4 个答案:

答案 0 :(得分:0)

$('#paragraph').appendTo('#div2')

答案 1 :(得分:0)

$('#div2').append('#paragraph'); 应该这样做!

只是一点注意事项: 将元素添加为父级的最后一个子级(#div2)时,请使用.append()。 如果您想要它作为第一个,您可以使用.prepend()

答案 2 :(得分:0)

这对我有用:

var block = document.querySelector('.block');
var parentNode = document.querySelector('#parent');
parentNode.insertBefore(block, parentNode.firstChild);

答案 3 :(得分:0)

Vanilla Javascript ...一个非常基本的示例,说明如何完成此操作:

将elements段落和div2定义为变量...

创建一个新的p元素,将textContent移动到要移动的div中。

将p元素附加到要移动的div,然后将段落的textContent分配给新的p元素。

从初始div1中删除初始p元素

// get the element of id paragraph
let target = document.getElementById('paragraph');
// get the element you wish to move it to
let div2 = document.getElementById('div2');

// a button to illustrate moving it from one element to another
let button = document.getElementById('button');

button.addEventListener('click', function() {
  // create a new p tag to append the element to
  let p = document.createElement('p');
  // append the new p tag to the div2 element
  div2.append(p);
  // assign the targets textContent to the new p element
  p.textContent = target.textContent;
  // remove the old p element from the initial div
  target.remove();
  button.remove();
})
#div1 {
background: #ddd;
}

#div2 {
background: #ff0;
}
<div>
  <div id="div1"><span>This is Div 1</span>
    <p id="paragraph">Lorem ipsum dolor sit amet, adipiscing pellentesque egestas.</p>
  </div>
  <input type="button" id="button" value="Click to move element">

  <div id="div2"><span>This is Div 2</span>
</div>

jQuery:

let para = $('#paragraph');
let div2 = $('#div2');

let btn = $('#button');

btn.click(function(){
  let el = $('<p></p>');
  div2.append(el);
  el.text(para.text());
  $('#div1').children()[1].remove();
  btn.remove();
})
#div1 {
background: #ddd;
}

#div2 {
background: #ff0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div id="div1"><span>This is Div 1</span>
    <p id="paragraph">Lorem ipsum dolor sit amet, adipiscing pellentesque egestas.</p>
  </div>
  <input type="button" id="button" value="Click to move element">

  <div id="div2"><span>This is Div 2</span>
</div>