Access attributes of d3.js element from database?

I am trying to access the cx and cy attributes of some specific SVG circles that I have already drawn on the screen using the d3.js.data () function, can anyone help? The code that is 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 new to d3.js and javascript, so I'm not sure if I approach this anyway to go forward, or maybe I skipped the built-in solution?

+42
javascript svg
Jul 04 2018-12-12T00:
source share
3 answers

Your code tries to get the svg attribute from the data element when what you really want is to get this attribute from the svg DOM element, as in:

 console.log(d3.selectAll(".mynode").attr("cx")); 

This will only give you an attribute for the first non-zero element of your choice; You can also filter your selection to get the DOM element you are looking for:

 console.log(d3.selectAll(".mynode").filter(_conditions_).attr("cx")); 

Or, if you want to access the attributes of all the selected elements, use this in each of your functions:

 d3.selectAll(".mynode").each( function(d, i){ if(d.someId == targetId){ console.log( d3.select(this).attr("cx") ); } } 
+63
Jul 05 2018-12-12T00:
source share

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: if .data () is not called (which is the case here), then the first argument d passed to .each will be undefined (and not " current dom node ", as all newbies would expect, including me); you get the current dom node through d3.select (this), which is true in the if statement itself at the very end - the error is in the if condition. The following is the correct version.

 d3.selectAll(".mynode").each(function(d,i){ var elt = d3.select(this); if (elt.attr("id") == "yourTargetIdGoesHere"){ console.log( elt.attr("cx") ); } }); 

script: fiddle (containing code for both versions, i.e. filter and each)

UPDATE: my answer suggested that you did not use .data () since you did not give the code for this; I later saw that you wrote that you used .data ()

in this case, depending on your data structure, replacing d.attr ("cx") with plain d.cx might work.

+12
May 21 '14 at 16:25
source share

There is an even simpler way: (pointer i provided)

 d3.selectAll("circle")[0][i].attributes.cx.value 

as can be seen here .

+11
Jun 29 '14 at 23:38
source share



All Articles