correct way to tell if my selection caught any existing elements
Javascriptd3.jsJavascript Problem Overview
I'm making a toggle in d3, and trying to avoid global variables.
I can go ahead and select the item as though it was already in the scene:
d3.select('#awesome_line_graph')
and then test to see if I caught anything using
if (d3.select('#awesome_line_graph')[0].every(function(d){return d===null})){
// draw awesome line graph
} else {
d3.select('#awesome_line_graph').remove()
}
but this testing for the zeroth element for maybe more than one null thing seems terrible and hacky. How should I do it instead? Apologies for not knowing much javascript.
Javascript Solutions
Solution 1 - Javascript
Use selection.empty()
. Also, if the selection is empty, there's no need to remove it.
Solution 2 - Javascript
I highly recommend you read Mike Bostock's D3 Workshop document. In it, he talks about how a selection returns an array of elements that match the selection criteria. Therefore, if the length of the array is greater than "0", you've properly matched and selected.
You may also want to read his documentation on "Nested Selections." I found it pretty useful.
I hope this helps.
Frank
Solution 3 - Javascript
In version d3.js v5, one can use
if(var n = d3.select('#awesome_line_graph').size() == 0) {
console.log("no DOM element selected.");
} else {
console.log(n + " DOM element(s) selected.");
}
Solution 4 - Javascript
Using length wont do as a single object containing all results will be returned in either cases. Maybe you could do something like ...
var selected = d3.select('#selected');
if (selected._group[0][0] == null) {
// nothing found
} else {
// found something
}