Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  61] [ 4]  / answers: 1 / hits: 52553  / 12 Years ago, thu, july 5, 2012, 12:00:00

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




  • The child1 id is the only known identifier.

  • The class parent and child2 are dynamic name and will change, so can't be used as identifiers.

  • needs to be vanilla JavaScript.



Thoughts?


More From » dom

 Answers
98

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...


[#84448] Wednesday, July 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;