I have the following structure:
<div class="parent">
<div id="child1">Content here</div>
<div class="child2">Content here</div>
</div>
At onload, I want to include a "holder" div, that holds all the parent's children like so:
<div class="parent">
<div id="holder">
<div id="child1">Content here</div>
<div class="child2">Content here</div>
</div>
</div>
Knowing only the "child1" id, how can I add a holder div around itself and siblings?
Considerations
Thoughts?
Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.
The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.
Seeing as this has to be JavaScript (and not jQuery) and you can only indentify the child1 by id you could do something as crude as this:
var child1 = document.getElementById("child1"),
parent = child1.parentNode,
contents = parent.innerHTML ;
parent.innerHTML = '<div id="holder">' + contents + '</div>';
Hope this helps...
He said no jQuery, this sounds like a homework assignment but:
var el = document.getElementById('child1');
var parent = el.parentNode;
parent.innerHTML = '<div id="holder">' + parent.innerHTML + '</div>';
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