score:4

Accepted answer

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>

score:3

use node()

d3.select("svg") - return d3 selection object
d3.select("svg").node() - return dom node

console.log(d3.select("svg") == d3.select("svg"))

console.log(d3.select("svg").node() == d3.select("svg").node())
<script src="//d3js.org/d3.v4.0.0-alpha.23.min.js"></script>

<svg></svg>


Related Query