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:
- A visual explanation of the Enter, Update and Exit Selections in D3js
- Using d3js to draw a bar chart with an axis and some basic transitions
- d3 Fundamentals: Creating a simple bar graph
- d3 Fundamentals : Understanding domain, range and scales in D3js
- How to get the data of a node in d3