Why are the d3 stroke styles I have set showing as an empty string in the debugger but red on screen? How do I access the stroke style?

rgb_jewel Source

I have a force-directed graph with multiple black coloured graph nodes and some red ones. My code is supposed to turn the node's stroke colour to #2291b97a when I click on a node but leave the ones that are red and black as they are.

I turn my nodes red based on certain conditions like this:

d3.select("svg").selectAll("g.node").each(function(d) {
            if(d == bpOperation) {
                this.firstChild.style = "stroke: red; stroke-width: 3"; 
                }
            }); 

My code changes the colour of the clicked node to #2291b97a, but turns the rest of the nodes' border to black - even the red ones.

svg.selectAll('g.node')
.every(element => element
        .every(g => (g.firstChild.classList.contains('on')) ? g.firstChild.classList.remove("on") : "true"));


//add on class   
this.firstChild.classList.add("on");

//if it contains an on class set colour to #2291b97a else check if the 
//stroke is red
svg.selectAll('g.node')
.every(element => element
        .every(g => (g.firstChild.classList.contains('on')) ? this.firstChild.style = "stroke: #2291b97a; stroke-width: 3" : ((g.firstChild.style = "stroke: red; stroke-width: 3"==true) ? g.firstChild.style = "stroke: red; stroke-width: 3" : g.firstChild.style = "stroke: black; stroke-width: 2")));

In this line I check if the style is set to red. If it is red, I set it to red again otherwise if it isn't I set it to black

((g.firstChild.style = "stroke: red; stroke-width: 3"==true) ? g.firstChild.style = "stroke: red; stroke-width: 3" : g.firstChild.style = "stroke: black; stroke-width: 2"));

For some reason this statement (g.firstChild.style = "stroke: red; stroke-width: 3"==true) always returns false and when I checked what was being actually saved in debug mode I saw that the stroke style for the red coloured node was an empty string "" even though on screen I can see it red.

So how do I access the stroke property I had changed? Am I even changing the colour correctly?

javascriptd3.jssvg

Answers

answered 6 months ago rgb_jewel #1

I was applying an inline style and it was showing an empty string in the attributes list because I never set it in the first place.

I had to replace this line

this.firstChild.style = "stroke: red; stroke-width: 3"; 

with this line

this.firstChild.setAttribute('style','stroke: red; stroke-width: 3;');

and likewise get the attributes in the other function like this

(g.firstChild.getAttribute('style') == "stroke: red; stroke-width: 3;")

comments powered by Disqus