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

I have an existing svg element, for example:

<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 ​​for the circles and link them as data back to the circles. I can do this with one:

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

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

This answer explains how to view all attributes in the console, but does not explain how to save or bind them to DOM elements.

+2
source share
1 answer

Does this work for you?

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

Source: https://habr.com/ru/post/1675754/


All Articles