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

How to select a node in d3js whose data has a certain value

Lets say that you created a d3 structure based upon some data and you now want to query that structure to select nodes whose data matches a certain value.

The below example 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 example, if you had a collection of circles with each node representing a country and the language spoken in the country is stored as a data attribute – ‘lang’. You could now easily get an array of all the circles 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...