D3 get attributes from element

I am trying to use basic d3 and I am trying to get the attributes of each of rectusing d3, but I cannot get anything.

Console screen

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

result

How can I access attributes rectusing something like d3.selectAll("rect").select("part1").attr(...)or something like that? I want to access the various attributes of all rect.

+4
source share
1 answer

You can get any attribute of an element using getter :

d3.select(foo).attr("bar")

This is basically a function attr()with one argument.

. : part1 part2. part1 x:

var svg = d3.select("svg");
var rects = svg.selectAll("foo")
  .data(d3.range(14))
  .enter()
  .append("rect")
  .attr("fill", "teal")
  .attr("y", 20)
  .attr("x", d => 10 + 12 * d)
  .attr("height", 40)
  .attr("width", 10)
  .attr("class", d => d % 2 === 0 ? "part1" : "part2");

d3.selectAll(".part1").each(function(d,i) {
  console.log("The x position of the rect #" + i + " is " + d3.select(this).attr("x"))
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Hide result
+8

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


All Articles