Skip to content
Advertisement

D3 get attributes from element

I am trying some basic d3 and i have been trying to get the attributes of each of the rect using d3 but I am not able to get anything.

Console Screen

When i try d3.selectAll("rect"), I get

result

How do can i access attributes of rect by using something like d3.selectAll("rect").select("part1").attr(...) or something similar? I want to access different attributes of all rect.

Advertisement

Answer

You can get any attribute of an element using a getter:

JavaScript

Which is basically the attr() function with just one argument.

Here is a demo. There are two classes of rectangles, part1 and part2. I’m selecting all part1 rectangles and getting their x positions:

JavaScript
JavaScript
Advertisement