简体   繁体   中英

Add div as only child of a node

I am trying to add div as only child to a node. and if that node already has any children make them children of the div.

original DOM looks like:

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

It doesn't use innerHTML , so you're not destroying any state of the elements being transferred.


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 .

Since .childNodes is a live list, its content is updated when you move one of its items to a different location. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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