Accessing d3.js element attributes from the datum?

前端 未结 4 1227
鱼传尺愫
鱼传尺愫 2021-01-30 20:28

I\'m trying to access the cx & cy attributes of some specific svg circles which i have already drawn to the screen using d3.js\'s .data() function, can anyone help out? The

相关标签:
4条回答
  • Your code is trying to get an svg attribute from an item of data, when what you really want is to get that attribute from the svg DOM element, as in:

    console.log(d3.selectAll(".mynode").attr("cx"));
    

    This will only give you the attribute for the first non-null element of your selection; You can also filter your selection to get the DOM element you are looking for:

    console.log(d3.selectAll(".mynode").filter(_conditions_).attr("cx"));
    

    Or, if you'd like to access the attributes of all selected elements, use this in your each function:

    d3.selectAll(".mynode").each( function(d, i){
      if(d.someId == targetId){
        console.log( d3.select(this).attr("cx") );
      }
    }
    
    0 讨论(0)
  • 2021-01-30 21:03

    The simplest here is to give each node a unique id and then select the node with the target id to run your transformation.

    0 讨论(0)
  • 2021-01-30 21:10

    The filter method in the accepted answer is correct. The second approach in the accepted answer (using .each) is incorrect, and contains the same error as the questioner was making: if .data() is not called (which is the case here), then first argument d passed to .each will be undefined (and not the "current dom node", as all newbies, including myself, would expect); the current dom node you get via d3.select(this), which is correct within the if statement at the very end - the error is in the if test condition. Correct version follows.

    d3.selectAll(".mynode").each(function(d,i){
        var elt = d3.select(this);
        if (elt.attr("id") == "yourTargetIdGoesHere"){
            console.log( elt.attr("cx") );
        }
    });
    

    fiddle: fiddle (containing code for both versions, i.e. filter and each)

    UPDATE: my answer was assuming that you didn't use .data(), since you did not give the code for that; later I saw that you wrote that you did use .data()

    in that case, depending on your data structure, replacing d.attr("cx") by plain d.cx might work.

    0 讨论(0)
  • 2021-01-30 21:18

    There is even simpler way: (providing index i is given)

    d3.selectAll("circle")[0][i].attributes.cx.value
    

    as it can be seen here.

    0 讨论(0)
提交回复
热议问题