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
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);
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>.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With