Reputation: 2110
Using the force layout in d3, I can happily add nodes as, say, an SVG group of a circle and some text:
var node = vis.selectAll(".node")
.data(nodes)
.enter().append("svg:g")
.attr("class", "node");
node.append("svg:circle")
.attr("r", 5);
node.append("svg:text")
.text(function(d) { return d.nodetext });
However, I would like to optionally add another element to the group, dependent on the node data: so if the data for this node contains an "image" attribute, I'd like to add a new child-element (an svg:image). It's easy to add the svg:image to all nodes (I just do it as I've done the circle and text above). It's also easy to dynamically change an attribute of an element you've already created (by having a function as the attribute's value, as per text
above). I do not know how to add an svg:image
child element only if the data contains an image
attribute. What's the best way of achieving this?
Upvotes: 2
Views: 3852
Reputation: 51819
Try selection.filter:
node.filter(function(d) { return d.image; }).append("image")
.attr("xlink:href", function(d) { return d.image; })
.attr("width", 16)
.attr("height", 16);
Upvotes: 11