Reputation: 79
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?
Upvotes: 0
Views: 763
Reputation: 780994
If you're willing to use jQuery, it has a wrapAll
method that does this for you.
$(node).children().wrapAll('<div id="oaa_web_accessibility_highlight"></div>');
Upvotes: 0
Reputation: 48761
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.
Upvotes: 2