jtr13
jtr13

Reputation: 1277

Get attributes of existing SVG elements and bind as data with d3.js

I have an existing svg element such as:

<svg width="300" height="200">
    <circle cx="50" cy="10" r="5" fill="green"></circle>
    <circle cx="100" cy="20" r="10" fill="green"></circle>
    <circle cx="150" cy="30" r="15" fill="green"></circle>
</svg>

I would like to extract the cx values of the circles and bind them as data back to the circles. I can do it with one:

var x = +d3.select('circle').attr('cx');
d3.select('circle').datum(x);

However I cannot figure out how to collect all of the cx values into an array and them join them to the circles. (Or perhaps there a more direct way to do this without the data array.)

This answer explains how to view all attributes in the console, but doesn't explain how to store them or bind them to DOM elements.

Upvotes: 3

Views: 2980

Answers (1)

glortho
glortho

Reputation: 13200

Does this work for you?

d3.selectAll('circle').datum(function() {
  return parseFloat(this.getAttribute('cx'));
});

Upvotes: 3

Related Questions