I am new to javascript and currently struggling with selecting the this object while trying to do a d3 selection. I\'ve made the following example, with a funct
Just for completeness, since this question has already two very good answers: you can avoid the confusion with this
if you use the third and second arguments combined. That's something that even D3 developers forget eventually.
In several D3 methods, the current DOM element is just the current index of the nodes' group. So, in the anonymous function...
.on("mouseover", function(_, i, n) {
... this
is just n[i]
, which you can just pass to the other functions. The _
here corresponds to the first argument, the datum: I'm using _
just to follow the convention that shows this argument is not used.
The nice thing about this approach is that you can even (for whatever reasons you have) use arrow functions:
d3.select("body").selectAll(null)
.data(["foo", "bar", "baz"])
.enter()
.append("p")
.text(String)
.on("mouseover", (_, i, n) => {
changeFont(n[i])
});
function changeFont(element) {
d3.select(element).style("font-size", "2em")
}
Of course, you can't get the DOM element using this
inside the arrow function.