Insert a div element as parent

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

提交回复
热议问题