BigBug
BigBug

Reputation: 6290

Using selectors to retrieve fill and stroke colors?

Extremely new to d3 and the concept of selectors - just wondering if it is possible to retrieve a color of an element using selectors?

For instance:

 var svgContainer = d3.select("body").append("svg")
                                     .attr("width", 200)
                                     .attr("height", 200);

 //Draw the line
 var circle = svgContainer.append("line")
                          .attr("x1", 5)
                          .attr("y1", 5)
                         .attr("x2", 50)
                         .attr("y2", 50)
                         .attr("stroke-width", 2)
                         .attr("stroke", "black");

What would i have to do in order to use selectors to retrieve the "stroke" attribute back? Is it possible to do something like circle.select("stroke") and have it give me the value "black" or something similar...?

Thanks in advance!

Upvotes: 0

Views: 26

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

You're confusing elements and their attributes -- selectors select the former, but not the latter. However, once you've selected an element, you can query its attributes:

var black = d3.select("line").attr("stroke");

Or use the D3 selection directly:

var black = circle.attr("stroke");

Upvotes: 1

Related Questions