Derick Kolln
Derick Kolln

Reputation: 633

Seperate elements in d3.js. Is there an array needed?

i got a little question about d3.js. On this example i can click on a node, it checks, if the array "a" i created before, got the element "element1" and if yes, it turns the stroke-width of the links between the nodes bigger into 22px and the others into 3px.

Now, here is my problem. I want now manipulate only these new seperated thin ones with stroke-width of 3px. How can i now get access to only these ones? Should i store them in an extra-array?

For example, i could create a new button and if i click on it, it will turn only these links with the size of 3px into green, but don't touch the other ones.

on("click", function(d, i){
    links.style("stroke-width", function(d){
                   return a.includes(d.element1) ? "22px" : "3px"; 
                });........

Upvotes: 0

Views: 79

Answers (2)

Mark
Mark

Reputation: 108512

I think I might understand now. The problem you are having with @EricGuan's solution is that he's selecting by the attribute stroke-width while you are using the style stroke width. I think your best bet is a .filter:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <script>
      
      var svg = d3.select('body')
        .append('svg')
        .attr('width','500px')
        .attr('height', '500px');
        
      var data = d3.range(10);
      
      var links = svg.selectAll('.link')
        .data(data)
        .enter()
        .append('path')
        .attr('d', function(d){
          return "M0," + (d * 50 + 3) + "L500," + (d * 50 + 3);
        })
        .style("fill", "none")
        .style("stroke", "steelblue")
        .style("stroke-width", function(d){
          return Math.random() > 0.5 ? '10px' : '3px';
        });
    
      links.filter(function(d){
        return this.style.strokeWidth === '3px';
      })
      .transition()
      .duration(2000)
      .style('stroke-width', '23px');
      
    </script>
  </body>

</html>

Upvotes: 1

Eric Guan
Eric Guan

Reputation: 15992

You can select elements by attribute.

d3.selectAll('line[stroke-width="3px"]')

Upvotes: 1

Related Questions