将div元素插入父项 [英] Insert a div element as parent
问题描述
但是,在其他地方,我们已经完成了以下任务:
var testElement = document.getElementByID('testID')
其中testID是元素的子元素被打倒在一个div。所以在我们完成插入之后,testElement仍然有效?
BTW:我没有使用jquery。
任何想法?
谢谢,
AJ
您可以使用 replaceChild
[docs] :
// `element`是要包装的元素
var parent = element.parentNode;
var wrapper = document.createElement('div');
//将包装器设为子(而不是元素)
parent.replaceChild(wrapper,element);
//将元素作为包装器的子元素
wrapper.appendChild(element);
只要不使用 innerHTML
(破坏和创建元素),对现有DOM元素的引用不会更改。
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.
这篇关于将div元素插入父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!