user773156
user773156

Reputation:

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!

Upvotes: 4

Views: 5367

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

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.

Upvotes: 2

Related Questions