简体   繁体   中英

d3js - adding a parent element to a selection

How can i add with d3.js a parent element to a selection. Lets say I have the following

<div class="i need a parent">...</div>
<div class="i need a parent">...</div>

and i want to modify this into

<a href="...">
    <div class="i need a parent">...</div>
</a>
<a href="...">
    <div class="i need a parent">...</div>
</a>

Any suggestion highly appreciated.

Not possible purely with d3, but easy enough with a little standard JavaScript

var selection = d3.selectAll('div.needparent');
selection.each(function() {
    var oldParent = this.parentNode;
    var newParent = document.createElement('a');
    oldParent.replaceChild(newParent, this);
    newParent.appendChild(this);
})

You can use d3 for some of the operations within the iteration, but since replaceChild requires standard JavaScript I stuck with that throughout.

One note of caution, if you have event handlers bound to the child elements, I'm not sure they'll be preserved with this approach.

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