Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a div element as parent

Tags:

javascript

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

like image 325
AJ. Avatar asked Aug 04 '11 08:08

AJ.


People also ask

How do you add a child to a parent div?

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

What is parent div in HTML?

A parent is an element that is directly above and connected to an element in the document tree. In the diagram below, the <div> is a parent to the <ul>.


2 Answers

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.

like image 67
Felix Kling Avatar answered Oct 07 '22 09:10

Felix Kling


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); 
like image 21
Quentin Avatar answered Oct 07 '22 10:10

Quentin