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.
When i try d3.selectAll("rect")
, I get
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
x
2
1
d3.select(foo).attr("bar")
2
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
1
15
15
1
var svg = d3.select("svg");
2
var rects = svg.selectAll(null)
3
.data(d3.range(14))
4
.enter()
5
.append("rect")
6
.attr("fill", "teal")
7
.attr("y", 20)
8
.attr("x", d => 10 + 12 * d)
9
.attr("height", 40)
10
.attr("width", 10)
11
.attr("class", d => d % 2 === 0 ? "part1" : "part2");
12
13
d3.selectAll(".part1").each(function(d,i) {
14
console.log("The x position of the rect #" + i + " is " + d3.select(this).attr("x"))
15
})
JavaScript
1
2
1
<script src="https://d3js.org/d3.v4.min.js"></script>
2
<svg></svg>