Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get parent element and write holder div for siblings

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?

like image 800
mika.el Avatar asked Jul 05 '12 11:07

mika.el


People also ask

What is the difference between parentNode and parentElement?

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.

How do we access the parent node of an element?

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.

What does $( Div parent select?

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.


2 Answers

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

like image 101
Mike Sav Avatar answered Oct 16 '22 10:10

Mike Sav


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>';
like image 25
anteatersa Avatar answered Oct 16 '22 10:10

anteatersa