开发者

Insert a div element as parent

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's parent. Then the div becomes the element's new parent.

But to complicate things, elsewhere we have already done things like:

var testElement = document.getElementByID('testID')

where testID is a child of the element to be warapped in a div. So after we have done our insertion will 开发者_如何转开发testElement still be valid?

BTW: I'm not using jquery.

Any ideas?

Thanks,

AJ


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.


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);


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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜