html - Is it possible to change <div> parent using javascript? - Stack Overflow

I need to change a div parent programmatically.For example <body><div id="div_a">

I need to change a div parent programmatically. For example

<body>
  <div id="div_a">
    <div id="child"></div>
  </div>

  <div id="div_b">
  </div>
</body>

I wonder if it is possible to change the div with id="child" parent to a div with id="div_b" ?

I have search, but nowhere close. But in case there is a similar question, please let me know.

Thank you

I need to change a div parent programmatically. For example

<body>
  <div id="div_a">
    <div id="child"></div>
  </div>

  <div id="div_b">
  </div>
</body>

I wonder if it is possible to change the div with id="child" parent to a div with id="div_b" ?

I have search, but nowhere close. But in case there is a similar question, please let me know.

Thank you

Share Improve this question asked Apr 1, 2020 at 1:50 LynLyn 5074 silver badges15 bronze badges 1
  • please be more specific, tou want to transform <div id="child to a <div id="div_b and move it outside <div id="div_a ? – Mister Jojo Commented Apr 1, 2020 at 2:11
Add a ment  | 

4 Answers 4

Reset to default 4

You can simply use appendChild and pass the node as the parameter. A node cannot be in two places at once, so it will move it to the proper location.

let child = document.querySelector("#child");
let parent = document.querySelector("#div_b");

parent.appendChild(child);
  <div id="div_a">
    <div id="child"></div>
  </div>

  <div id="div_b">
  </div>

In pure JS, you can use document.querySelector (or document.getElementById) and Node.appendChild to append the #child div to the #div_b div. Since a node cannot exist in more than one place, this automatically also removes it from #div_a:

document.querySelector('#div_b').appendChild(document.querySelector('#child'));
// or document.getElementById('div_b').appendChild(document.getElementById('child'));
<body>
  <div id="div_a">
  Div A!
    <div id="child">I am a child of Div A</div>
  </div>
  <hr/>
  <div id="div_b">
  Div B!
  </div>
</body>

You need to add the element to the new parent, then remove it from the old one. If you can use JQuery you can do it easily with

jQuery("#child").detach().appendTo('#div_b')

with JavaScript

var tmp = document.getElementById('child');
document.getElementById('div_b').appendChild(tmp.cloneNode(true));
tmp.remove();

Depending on the your application you may want to use querySelector or querySelectorAll to get the div with id="child". Then using [insert element var].classlist() you can .remove('child') and then .add('div_b').

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744831687a4596122.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信