Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'd3.select("svg") == d3.select("svg")' resolve to 'false'?

I am just curious as to why d3.select("svg") == d3.select("svg") resolves to false and not true.

With D3 loaded in my browser (I tried chrome and FF), I typed that line into the console and it gave me that surprising result.

I used D3 version 5

The html body looks like this:

<body>
<svg></svg>
</body>
like image 951
namjo Avatar asked Mar 04 '23 18:03

namjo


1 Answers

The other answer provides an alternative (and the correct one by the way) to your problem. My goal here is to explain why you got the false.

This boils down to the old and famous case of comparing objects ({} !== {}) in JavaScript:

console.log({} === {})

You can read more about this subject by looking at the answers to this question and this question. The first answer to this question is also quite interesting and didactic.

Back to D3:

In D3 v3 and below selections are arrays, while in D3 v4 and above (like V5, the one you're using), selections are objects. Both will return object for typeof:

const svg = d3.select("svg");
console.log(typeof svg)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

And, in both cases (arrays or objects), the comparison will return false.

Because of that, even if two different selections point to the same DOM element, the selections themselves, which are objects, are different:

const svg1 = d3.select("svg");
const svg2 = d3.select("svg")
console.log(svg1 === svg2)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

Finally, regarding your comment, you're using the local variable wrong: you have to set it to the node, not to the selection. The API is clear:

local.set(node, value) <>

Sets the value of this local on the specified node to the value, and returns the specified value. (emphasis mine)

If you use it correctly, it will work:

const a = d3.select("svg");
const b = d3.select("svg");
const local = d3.local();
local.set(a.node(), 561);
console.log(local.get(b.node()))
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
like image 97
Gerardo Furtado Avatar answered Mar 13 '23 01:03

Gerardo Furtado