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. When i try d3.selectAll('rect'), I get How
Solution 1:
You can get any attribute of an element using a getter:
d3.select(foo).attr("bar")
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:
var svg = d3.select("svg");
var rects = svg.selectAll(null)
.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"))
})
<scriptsrc="https://d3js.org/d3.v4.min.js"></script><svg></svg>
Post a Comment for "D3 Get Attributes From Element"