I'm trying to access the cx & cy attributes of some specific svg circles which i have already drawn to the screen using d3.js's .data() function, can anyone help out? The code that's trying to access it is below.
d3.selectAll(".mynode").each( function(d, i){
if(d.someId == targetId){
console.log( d.attr("cx") ); // just trying to demo my point, doesn't work
}
}
I'm quite new to d3.js & javascript, so i'm not sure if i'm approaching this back to front anyways or perhaps i may have missed an inbuilt solution?
Your code is trying to get an svg attribute from an item of data, when what you really want is to get that attribute from the svg DOM element, as in:
This will only give you the attribute for the first non-null element of your selection; You can also filter your selection to get the DOM element you are looking for:
Or, if you'd like to access the attributes of all selected elements, use
this
in your each function:There is even simpler way: (providing index
i
is given)as it can be seen here.
The filter method in the accepted answer is correct. The second approach in the accepted answer (using .each) is incorrect, and contains the same error as the questioner was making: if .data() is not called (which is the case here), then first argument d passed to .each will be undefined (and not the "current dom node", as all newbies, including myself, would expect); the current dom node you get via d3.select(this), which is correct within the if statement at the very end - the error is in the if test condition. Correct version follows.
fiddle: fiddle (containing code for both versions, i.e. filter and each)
UPDATE: my answer was assuming that you didn't use .data(), since you did not give the code for that; later I saw that you wrote that you did use .data()
in that case, depending on your data structure, replacing d.attr("cx") by plain d.cx might work.