tic
tic

Reputation: 4189

D3: get element attribute inside selectAll

<html>
    <svg></svg>
    <script src="d3.v4.min.js"></script>
    <script>
            var svg = d3.select("svg")
                .attr("width", 1000)
                .attr("height", 500)
            ;
            for (var i=0;i<3;i++) {
            svg.append("rect")
                .attr("x",i*80)
                .attr("y",i*40)
                .attr("width",30)
                .attr("height",30)
            ;
            }
            svg.selectAll("rect")
                .transition()
                .duration(500)
                .attr("x",2*d3.select(this).attr("x"))
            ;
    </script>
</html>

The line with d3.select(this).attr("x") returns an error. So, which is the right code to read x attr of each element?

Upvotes: 0

Views: 1678

Answers (1)

Ian
Ian

Reputation: 34489

The attr function of d3 takes either a value, or a function. In your example you're passing it a constant value (which is supposed to be the body of a function).

Therefore the d3.select(this) is going to operate on whatever this is in scope, most likely the global object. Instead wrap this in a function like so:

.attr("x", function() { 2 * d3.select(this).attr("x"); })

Alternatively you could use the following approach (version dependant)

.attr("x", (d, i, elements) => 2 * d3.select(elements[i]).attr("x"));

Note that currently you're also not applying any protection on the x value, I would seriously consider throwing it through a parseFloat() before trying to do any arithmetic on it.

Upvotes: 4

Related Questions