Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...