Reputation: 436
newbie d3.js here, i'm trying to understand the sample of stacked bar chart using d3.stack()
(note : not d3.layout.stack()
) from the sample link : http://bl.ocks.org/mbostock/3886208 (by Mike Bostock)
I'm trying to access the fill attribute of each svg group elements which each represents a single 'layer' / age group. To do so, I do a little modification at the "enter" part :
var seriesG = g.selectAll(".serie")
.data(function(){return stackedColumns;})
.enter().append("g")
.attr("class", "serie")
.attr("fill", function(d) {return z(d.key); });
Since console.log(seriesG);
resulted in zi {_groups: Array[1], _parents: Array[1]}
, i figured that the seven svg group elements that represents the seven age range groups is accessible in the _groups
member object.
Now, I can access each svg group element by this basic recursive routine :
seriesG._groups.forEach(function(d, i){
console.log(d);
});
which displays [g, g, g, g, g, g, g]
in the browser element inspector console (opera). What I'm trying to figure out is the correct syntax to access the fill attribute of the 'd' datum. And since by observing the browser console I know that the 'fill' is the member of 'outerHTML'
member attribute of the 'd' datum, first I must know how to access this 'outerHTML' attribute. I have tried various syntax :
console.log(d.attr("outerHTML"));
console.log(d.attr.outerHTML);
console.log(d.outerHTML);
console.log(d["outerHTML"]);
The first two tries resulted in Uncaught TypeError: d.attr is not a function
, while the remaining two are undefined
operations.
So, in the short version of my question is : "What is the correct syntax to access the fill of each svg group element created using d3.stack()
?"
My ultimate goal is to add various functionality similiar to this sample link : http://bl.ocks.org/KatiRG/f7d064cd9c3efbc3c360
Upvotes: 0
Views: 1939
Reputation: 1
You can use .getAttribute()
This way : element.getAttribute('fill')
More informations here :https://developer.mozilla.org/fr/docs/Web/API/Element/getAttribute
Upvotes: 0
Reputation: 108512
First, don't use _groups
. This is meant to be private to the selection object. You should be using the .nodes method.
Second, my question is what do you want to do with those fills?
The code you are trying to write is this:
seriesG.nodes().forEach(function(d){
console.log(d3.select(d).attr('fill'));
});
But, depending on the purpose, and since you know your keys (in the example you link to these are "65 Years and Over", "45 to 64 Years", etc..), then the fill value for any "key" can simply be returned as:
z("65 Years and Over");
Upvotes: 2