简体   繁体   中英

D3 .append() with variable

Suppose I have:

var parent = d3.select('g.someElement');

I'm looking to be able to do something along the lines of:

function addContent(content) {
    // content is a D3Selection or SVGElement
    parent.append(content);
}

I'm wondering if there is a way of appending already-defined SVGElements using D3 without having to unravel their tag name and other properties to be able to do it according to how selection.append() is specified. Basically, a lot like how .appendChild() works in vanilla JS.

Thanks!

As explained in the documentation you've linked to, the argument to .append() can be a function that returns the DOM element to be appended. Quick demo :

var element = document.createElement("div");
element.innerHTML = "foo";

d3.select("body").append(function() { return element; });

The argument to .append() really has to be a function, you can't just pass element to it.

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