JavaScript get parent element and write holder div

2020-02-10 17:01发布

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?

3条回答
我命由我不由天
2楼-- · 2020-02-10 17:49

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

查看更多
Evening l夕情丶
3楼-- · 2020-02-10 17:56

i wrote a litte-snipped to travel through DOM to find the first matching parentNode.

Hope this helps someone, sometime.

(/¯◡ ‿ ◡)⊃━☆゚. * ・ 。゚,

function getFirstParentMatch(element, selector) {
  if (!element) {return element};
  element.matches(selector) || (element = (element.nodeName.toLowerCase() === 'html' ? false : getFirstParent(element.parentNode, selector)));
  return element;    
}
查看更多
▲ chillily
4楼-- · 2020-02-10 18:01

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>';
查看更多
登录 后发表回答