简体   繁体   English

将div添加为节点的唯一子节点

[英]Add div as only child of a node

I am trying to add div as only child to a node. 我试图将div作为唯一的子项添加到节点。 and if that node already has any children make them children of the div. 如果该节点已经有任何子节点,则使它们成为div的子节点。

original DOM looks like: 原始DOM看起来像:

<a href = "">
  <span id="gsp" > </span>
  <span id="gbsp"> some text </span>
</a>

I want the output to be: 我希望输出为:

<a href = "">
  <div id="oaa_web_accessibility_highlight">  
    <span id="gsp" > </span>
    <span id="gbsp"> some text </span>
  </div>
</a>

instead, below snippet gives me: 相反,下面的片段给了我:

<a href = "">
  <div id="oaa_web_accessibility_highlight">  </div>
    <span id="gsp" > </span>
    <span id="gbsp"> some text </span>
</a>

I am trying to use the below snippet, but it is not working. 我试图使用下面的代码片段,但它无法正常工作。

var new_div_element = this.document.createElement('div');
new_div_element.id = 'oaa_web_accessibility_highlight';
node.insertBefore(new_div_element, node.childNodes[0]);
for (var i =0; i < node.childNodes.length; i++) {  
  if (i == 0) continue;        
  node.childNodes[0].appendChild(node.childNodes[i]);        
}

please can anyone help me on this? 请有人可以帮我吗?

Do it like this: 像这样做:

var new_div_element = document.createElement('div');
new_div_element.id = 'oaa_web_accessibility_highlight';

while (node.firstChild) {  
      new_div_element.appendChild(node.firstChild);        
}

node.appendChild(new_div_element);

This empties the children of node into new_div_element , and then appends new_div_element to the now empty node . 这会将node的子node清空为new_div_element ,然后将new_div_element附加到现在为空的node

It doesn't use innerHTML , so you're not destroying any state of the elements being transferred. 它不使用innerHTML ,因此您不会破坏正在传输的元素的任何状态。


FYI, the reason yours didn't work properly was that your loop is incrementing i , but you're removing elements from the .childNodes list when you do the .appendChild . 仅供参考,你的工作不正常的原因是你的循环正在递增i ,但是当你执行.appendChild时,你将从.childNodes列表中删除元素。

Since .childNodes is a live list, its content is updated when you move one of its items to a different location. 由于.childNodes是实时列表,因此当您将其中一个项目移动到其他位置时,其内容会更新。 As a result, after the first child is removed, the second child takes its place at that index. 结果,在移除第一个孩子之后,第二个孩子取代该指数。 Since your i is incremented, it skips passed the one(s) that were relocated in the list. 由于你的i递增,它跳过了在列表中重新定位的那个。

如果您愿意使用jQuery,它有一个wrapAll方法可以为您执行此操作。

$(node).children().wrapAll('<div id="oaa_web_accessibility_highlight"></div>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM