apdm apdm - 2 months ago 5
Javascript Question

How can I get the equivalent to a "this" keyword from d3 using d3.select()?

I have a d3 element which calls a function called

tick
.

g.append("g")
.attr("clip-path", 'url(' + $location.path() + '#clip)' )
.append("path")
.datum(data)
.attr("class", "line")
.transition()
.duration(500)
.ease(d3.easeLinear)
.on("start", tick);


Within the function tick, if I do
console.log(this)
I get something like the following printed to the console

<path class="line"></path>


However, if I do
console.log(d3.select("line"))
I get a huge object that I cannot manipulate the way I can using the
this
keyword. What is the equivalent
d3
method to select an element and return the equivalent of the
this
?

Answer

The "equivalent" is:

console.log(d3.select("line").node())

Given this simple snippet:

<svg width="100" height="100">
    <circle cx="40" cy="40" r="20" fill="teal"></circle>
</svg>

var circle = d3.select("circle");
console.log(circle.node());
console.log(circle);

console.log(circle.node()) gives you:

<circle cx="40" cy="40" r="20" fill="teal"></circle>

While console.log(circle) gives you:

zi {_groups: Array[1], _parents: Array[1]}

Note: I put quotes in "equivalent" because this depends on many things. So, that's the equivalent for your specific question.

Comments