Insert a div element as parent

后端 未结 4 1991
失恋的感觉
失恋的感觉 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:35

    In pure JS you can try something like this...

    var wrapper = document.createElement('div'); 
    var myDiv = document.getElementById('myDiv'); 
    wrapper.appendChild(myDiv.cloneNode(true)); 
    myDiv.parentNode.replaceChild(wrapper, myDiv);
    
    0 讨论(0)
  • You can use replaceChild [docs]:

    // `element` is the element you want to wrap
    var parent = element.parentNode;
    var wrapper = document.createElement('div');
    
    // set the wrapper as child (instead of the element)
    parent.replaceChild(wrapper, element);
    // set element as child of wrapper
    wrapper.appendChild(element);
    

    As long as you are not using innerHTML (which destroys and creates elements), references to existing DOM elements are not changed.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-08 05:54

    Here is another example, only the new element wraps around 'all' of its child elements.

    You can change this as necessary to have it wrap at different ranges. There isn't a lot of commentary on this specific topic, so hopefully it will be of help to everyone!

    var newChildNodes = document.body.childNodes;  
    var newElement = document.createElement('div');
    
    newElement.className = 'green_gradient';
    newElement.id = 'content';        
    
    for (var i = 0; i < newChildNodes.length;i++) {
        newElement.appendChild(newChildNodes.item(i));
        newChildNodes.item(0).parentNode.insertBefore(newElement, newChildNodes.item(i));
    }
    

    You will want to modify the 'document.body' part of the newChildNodes variable to be whatever the parent of your new element will be. In this example, I chose to insert a wrapper div. You will also want to update the element type, and the id and className values.

    0 讨论(0)
提交回复
热议问题