JavaScript gets the parent element and writes a div holder for siblings

I have the following structure:

<div class="parent">
  <div id="child1">Content here</div>
  <div class="child2">Content here</div>
</div>

In onload, I want to include a div holder that contains all the parent children:

<div class="parent">
  <div id="holder">
    <div id="child1">Content here</div>
    <div class="child2">Content here</div>
  </div>
</div>

Knowing only the identifier "child1", how can I add a div holder around me and my siblings?

Questions

  • The identifier "child1" is the only known identifier.
  • The class "parent" and "child2" are a dynamic name and will change, so they cannot be used as identifiers.
  • must be vanilla javascript.

Thoughts?

+11
source share
3 answers

, JavaScript ( jQuery), id1 id, - , :

var child1 = document.getElementById("child1"),
    parent = child1.parentNode,
    contents = parent.innerHTML ;
    parent.innerHTML = '<div id="holder">' + contents + '</div>';

, ...

+30

, jQuery, , :

var el = document.getElementById('child1');
var parent = el.parentNode;
parent.innerHTML = '<div id="holder">' + parent.innerHTML + '</div>';
+2

I wrote a small excerpt to go through the DOM to find the first matching parentNode.

Hope this helps someone someday.

(/ Β―β—‘ β€Ώ β—‘) βŠƒβ” β˜† ゚. * ο½₯q ゚,

function getFirstParentMatch(element, selector) {
  if (!element) {return element};
  element.matches(selector) || (element = (element.nodeName.toLowerCase() === 'html' ? false : getFirstParent(element.parentNode, selector)));
  return element;    
}
0
source

All Articles