Skip to content Skip to sidebar Skip to footer

Getting Attribute Values Of Multiple Elements

I want to get attribute values of the multiple elements in a selection as an array, but I cannot find a concise way. For example, in a svg element, there are some circles and you n

Solution 1:

If I'm understanding correctly, you want to get a list of the cx values. So, here's one way you could do that.

var cxs = [];
d3.selectAll("circle")[0].forEach(function(circle) {
  cxs.push(circle.getAttribute('cx'));
});

To make it a little shorter you could use map()

var cxs = d3.selectAll("circle")[0].map(function(circle) {
  return circle.getAttribute('cx');
});

Solution 2:

d3 v7 answer

The nodes() function returns an array of the underlaying element.

const cxs = d3.selectAll("circle").nodes().map(circle => 
  circle.getAttribute('cx');
});

Post a Comment for "Getting Attribute Values Of Multiple Elements"