In most of the
D3 examples,
data elements, usually SVG objects, are added using the
selectAll()
method.
This quickly becomes a problem when one tries to use the same element, e.g. SVG
text
, for different
parts of the data visualization.
A simple approach is to use the
class
tag. For this, we use the
classed()
method.
For the following example code:
svg.selectAll('text')
.data(data)
.enter().append('text')
.attr('y', function(d){return y(d.y);})
.attr('x', function(d){return x(d.x);})
.text(function(d){return d.name;});
we modify it to use classes as follows:
svg.selectAll('.myclass')
.data(data)
.enter().append('text')
.classed('myclass', true)
.attr('y', function(d){return y(d.y);})
.attr('x', function(d){return x(d.x);})
.text(function(d){return d.name;});
Instead of selecting all the
text
elements with the selector
selectAll()
,
we select all the elements with the class name
myclass
.