JavaScript 获取父元素并为兄弟姐妹写入持有人 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11343717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:32:59  来源:igfitidea点击:

JavaScript get parent element and write holder div for siblings

javascriptdomelementparent

提问by mika.el

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,它包含所有父母的孩子,如下所示:

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

只知道“child1”id,如何在自身和兄弟姐妹周围添加一个持有人 div?

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.
  • “child1”id 是唯一已知的标识符。
  • 类“parent”和“child2”是动态名称并且会改变,因此不能用作标识符。
  • 需要是普通的 JavaScript。

Thoughts?

想法?

回答by Mike Sav

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:

看到这必须是 JavaScript(而不是 jQuery)并且您只能通过 id 识别 child1,您可以做一些像这样粗糙的事情:

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

Hope this helps...

希望这可以帮助...

回答by anteatersa

He said no jQuery, this sounds like a homework assignment but:

他说没有 jQuery,这听起来像是家庭作业,但是:

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

回答by stephanfriedrich

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

我写了一个小片段来遍历 DOM 以找到第一个匹配的 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;    
}