Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing d3.js element attributes from the datum?

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?

like image 546
Mike Winter Avatar asked Jul 04 '12 23:07

Mike Winter


People also ask

What does .data do in D3?

data() D3 is data driven. The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc.

What is enter () and exit () in D3 JS?

enter() function creates the initial join of the data with our DOM elements. Thus selecting only the elements that were not in the DOM yet. merge() function will select the DOM elements that did not exist in the DOM before and the ones that did. exit() function will select the DOM elements that are left from the join.

What is attr in D3?

attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.

What is datum in JavaScript?

The Datum JavaScript object is unique to Service Manager. This JavaScript object was deprecated as of ServiceCenter 6.1 because this object's methods can only return true or false boolean values. You can use the SCFile or SCDatum objects in place of this object to take advantage of the improved return code values.


2 Answers

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:

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

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:

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

Or, if you'd like to access the attributes of all selected elements, use this in your each function:

d3.selectAll(".mynode").each( function(d, i){   if(d.someId == targetId){     console.log( d3.select(this).attr("cx") );   } } 
like image 61
Josh Avatar answered Oct 06 '22 18:10

Josh


There is even simpler way: (providing index i is given)

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

as it can be seen here.

like image 20
VividD Avatar answered Oct 06 '22 19:10

VividD