correct way to tell if my selection caught any existing elements
Use selection.empty()
. Also, if the selection is empty, there's no need to remove it.
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
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.");
}