Be the first user to complete this post
|
Add to List |
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');
Also Read:
- Creating an Animated Ring or Pie chart in d3js
- Render a d3js Tree as a React Component
- d3 Fundamentals: Creating a simple bar graph
- A visual explanation of the Enter, Update and Exit Selections in D3js