将div元素插入父项 [英] Insert a div element as parent

查看:73
本文介绍了将div元素插入父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如果以下是可能的,让我们说一个dom元素,我们想把这个元素包装在一个div中。所以在元素和它的父代之间插入一个div。然后,div成为元素的新父母。



但是,在其他地方,我们已经完成了以下任务:



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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆