score:73

Accepted answer

update (july 8th 2016) this answer applies to d3 v3.x — not v4.x. for the latter version, see tim hayes's answer, also on this page. or... just swap attr with attrs in my answer below, and don't forget to require/import/script-embed d3-selection-multi. and... don't miss the bit about using .each, which may be useful to you.


yeah, it's possible by passing in a hash (like jquery's css() method):

d3.select('body').append('svg').selectall('circle')
  .data(data)
.enter().append('circle')
  .attr({
    cx: function (d) { return d.x; },
    cy: function (d) { return d.y; },
    r:  function (d) { return d.r; }
  });

this works for style() as well.

if the reoccurring function (d) {} start to feel like too much, this is another approach:

d3.select('body').append('svg').selectall('circle')
  .data(data)
  .enter().append('circle')
  .each(function (d) {
    d3.select(this).attr({
      cx: d.x,
      cy: d.y,
      r:  d.r
    });
  })

note: this feature only exists in d3.js v2.10.0 or higher

score:73

this is an old post, but i found it while googling around for an answer. the accepted answer no longer works in d3 v4.0.

moving forward, you can do the same by using the attrs() method. but attrs() is only supported if you load the optional d3-selection-multi script.

so using the example above, it would look like this in d3 v4.0:

// load d3-selection-multi as separate script
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>

d3.select('body').append('svg').selectall('circle')
  .data(data)
  .enter().append('circle')
  .attrs({
    cx: function (d) { return d.x; },
    cy: function (d) { return d.y; },
    r:  function (d) { return d.r; }
  });

Related Query

More Query from same tag