Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Selecting a node in d3js based upon the value of its data

How to select a node in d3js whose data has a cer­tain value

Lets say that you cre­ated a d3 struc­ture based upon some data and you now want to query that struc­ture to select nodes whose data matches a cer­tain value.

The below exam­ple uses lodash for brevity.


// The container is probably going to be your svg file function selectNodesWithProperty(container, key, value){ var nodes = d3.selectAll(container). select(function(d, i) { return d[key] === value ? this : -1; }); return _.without(nodes[0],-1); }

For exam­ple, if you had a col­lec­tion of cir­cles with each node rep­re­sent­ing a coun­try and the lan­guage spo­ken in the coun­try is stored as a data attribute — ‘lang’. You could now eas­ily get an array of all the cir­cles whose lang value is ‘EN’ using

selectNodesWithProperty('svg circle', 'lang', 'EN');

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...