Using d3.js it’s possible to attach arbitrary attributes from the data to SVG elements, in this example a title which will be used for a tooltip:
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("title", function(d) { return d.title; })
Is there a way to attach an attribute only if it is present in the data? (i.e. in this example if the title was missing from the data it wouldn’t add the title attribute at all)
If the value of the attribute is null or undefined, then selection.attr removes the specified attribute. If there is no attribute defined, then setting the attribute to null or undefined has no effect. So, as long as the value of
d.titleis null or undefined when missing (and not the empty string), then your code will only set the “title” attribute when present.