Insert a div element as parent

后端 未结 4 2001
失恋的感觉
失恋的感觉 2020-12-08 05:26

I\'m just wondering if the following is possible, lets say we have a dom element and we want to wrap this element in a div. So a div is inserted between the element and it\'

4条回答
  •  长情又很酷
    2020-12-08 05:42

    Assuming you are doing your manipulation using standard DOM methods (and not innerHTML) then — yes.

    Moving elements about does not break direct references to them.

    (If you were using innerHTML, then you would be destroying the contents of the element you were setting that property on and then creating new content)

    You probably want something like:

    var oldParent = document.getElementById('foo');
    var oldChild = document.getElementById('bar');
    var wrapper = document.createElement('div');
    oldParent.appendChild(wrapper);
    wrapper.appendChild(oldChild);
    

提交回复
热议问题