Kuan
Kuan

Reputation: 11389

How to override the inline style by applying a new class in D3

All:

I used D3 to add style to SVG element like:

svg.append("rect")
   .attr("id", "testclass")
   .classed("hascolor", true)
   .style("fill", "red");

Then I define another class:

.nocolor{
    fill: transparent;
}

And when I want to apply this class to change style like:

svg.select("#testclass")
   .classed("nocolor", true);

The class of RECT changed, but the style did not apply( it only works when I use JS to change the style directly). I wonder if anyone could help with this to enable style changing by class on it?

Thanks

Upvotes: 1

Views: 3839

Answers (2)

ecarrizo
ecarrizo

Reputation: 2809

The inline styles has priority over the css style.

(I know that maybe this exact portion of code is not going to work in your case but is just for demonstrative proposes). Here is a Jquery example, that you can test the style priority over inline style, first class that apply a rule and second class that apply a rule with !important.

HTML:

 <div id='theOne' style="color: green;" class="colorRed"> Something that needs to be colored </div>

CSS:

.colorRed {
    color: red;
}
.colorBlack {
    color: black!important;
}

Jquery:

$('#theOne').addClass('colorBlack');

Fiddle

So posibles solutions to your problem are:

1) Add the rule fill: transparent as 'style' attribute.

2) Use a css class instead of the attribute style in the first step.

3) Add !important to the css Rule.

Upvotes: 2

Maciej Kwas
Maciej Kwas

Reputation: 6419

The thing is that inline styles are more important than attributes from any selector, like from class you used, se even new class is applied, the inline style still exists thus is more important, however you can use !important rule which will override inline styling.

First things that came to mind:

.nocolor{
    fill: transparent !important;
}

or

svg.select("#testclass").style("fill", "transparent");

Upvotes: 0

Related Questions