简体   繁体   中英

Updating certain nodes' style in d3js force layout

whats the simplest way to update the style of nodes, that are already drawn ? In this case, the layout is created, with all the links, nodes - perfect. Then an array is passed to the directive and if the node name is in that array, I want to change its colour.

example:

var names = ["tom","john"]; // this data comes in...


                d3.select("node").select("circle").style("fill", function (d) {
                   // I check if the node name is in array, if so change its colour to green.
                    if (names.indexOf(d.name) > -1) {
                        return "green";
                    } else
                        return "red";

                });

Try using a selection filter

d3.selectAll("node").selectAll("circle")
  .filter(function(d){
    return names.indexOf(d.name) < 0;
  })
  .style("fill", "red");

ahmohamed's method is good. Another alternative: When you're building the page, add the names as values of id or as an additional class for each node. Then you can select the element you want using that id or class, perhaps with a compound CSS selector. For example if you make the names id s, you can do:

d3.selectAll("node").selectAll("#tom").style("fill", "green");

Here "#tom" refers to all DOM elements with id="tom" . If there are things other than circles with "tom" as id, this should work:

d3.selectAll("node").selectAll("circle#tom").style("fill", "green");

That says to get circle s with id="tom" .

(It may be possible to combine #tom and #john with some kind of OR operator in the selector. I'm not sure.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM