Apply multiple styles with .style() method in D3.js
Edit (2021):
Note: I claimed (in initial version of this answer) that there's no embedded method to solve the OP's problem. And, as of D3 v6.7.0 you still cannot pass your styles as an object directly to
.style()
method
Two options you got by the time of this writing:
- loop through your styles object and apply the styles incrementally
const style = {"width":"100px","height":"100px","background-color":"lightgreen"}
Object.entries(style).forEach(([prop,val]) => d3.select("#test").style(prop,val))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>
d3 chart: how to set multiple css properties for d3 chart
Here's an example, you can pass a style object into the .style()
function with d3.js V3:
const width = 200;
const svg = d3.select('svg')
.attr('width', '100%')
.attr('viewBox', `0 0 ${width} ${width}`);
svg.append("text")
.attr("x", width / 2 )
.attr("y", 0)
.style({
'alignment-baseline': "hanging",
"text-anchor": "middle",
"font-size": 12,
})
.text("Title of Diagram");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<svg>
</svg>
D3.js setting multiple styles dynamically
In this case, I would use the .each()
function (or maybe .call()
) to run a function on each (or all at once) selected elements. In this function, you can, based on data or something else, add styles, attributes etc.
The basic code would look like this.
sel.each(someFunc);
function someFunc(d) {
if(d.something) { d3.select(this).style("foo", "bar"); }
if(d.somethingElse) { d3.select(this).attr("bar", "foo"); }
}
Can you set style in d3 via something like foo.style({color:blah, background:blah})?
Only works on D3 v3:
To quote the documentation:
If you want to set several style properties at once, use an object literal like so:
selection.style({'stroke': 'black', 'stroke-width': 2})
This isn't possible with functions though, so in your case you still have to use the "long form".
style method does not take object
According to d3.js documentation https://github.com/d3/d3-selection#selection_style selection.style(name,value)
accepts single name-value pairs (value can be a constant or a function accepting d,i,data as usual), but not objects
If you want to set multiple style properties, you need to use multiple style() functions
d3.selectAll('.item')
.style('background', function(d){ return d.background; })
.style('width', function(d){return d.width; });
EDIT: Or use the d3-selection-multi library as Eric Guan pointed in his answer: https://stackoverflow.com/a/41474957/79536
D3: adding style and class to DIV results in styles discarded
You just forget the "px":
var aWindow = d3.select(parent)
.append("div")
.attr("class",aClass)
// <div style="top:30px; left:40px; width:50px; height:50px;"></div>
.style("top",y + "px")
.style("left",x + "px")
.style("width",width + "px")
.style("height",height + "px");
Can selectAll() in d3 js take css style also as parameter?
d3.selectAll(selector)
Selects all elements that match the specified selector string. The elements will be selected in document order (top-to-bottom). If no elements in the document match the selector, or if the selector is null or undefined, returns an empty selection. For example, to select all paragraphs:
var paragraph = d3.selectAll("p");
1) In your example, .legend
is a class selector. It is being passed as an argument to selectAll
to match all DOM elements that have a class of legend
.
2) .legend
is not a CSS style itself. But it can be used in CSS as a selector to apply some style properties to the elements that match said selector.
3) selectAll
accepts only one argument: a selector string. That could simply be "p"
or it could be ".content .items > li"
.
Have a look below how we can use both CSS & D3 to apply different styles.
d3.selectAll(".highlight")
.style({
"color": "green"
})
nav a {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<nav>
<ul>
<li><a href="#nowhere" title="Lorum ipsum dolor sit amet">Lorem</a></li>
<li><a href="#nowhere" title="Aliquam tincidunt mauris eu risus">Aliquam</a></li>
<li><a href="#nowhere" title="Morbi in sem quis dui placerat ornare" class="highlight">Morbi</a></li>
<li><a href="#nowhere" title="Praesent dapibus, neque id cursus faucibus">Praesent</a></li>
<li><a href="#nowhere" title="Pellentesque fermentum dolor" class="highlight">Pellentesque</a></li>
</ul>
</nav>
Related Topics
Find Td with Specific Text, and Operate on the Td Right After That One
Trigger Event Using Jquery on CSS Change
CSS Dropdown Menu: Add Delay on Mouse Out
Make Webelement Visible via Selenium with Python with JavaScript
Ie < 9 CSS3 Transition Effect Cheats
Make the on Scroll Growing <Path> to Dashed Line
Export SASS/Scss Variables to JavaScript Without Exporting Them to CSS
Changing Visibility Using JavaScript
Capture/Save/Export an Image with CSS Filter Effects Applied
Link on Certain Position of an Image Background Which Is Responsive
Wrapping Text Inside Irregular Shapes
Does the JavaScript Onclick Event Not Work on <Select> <Option>'S
How to Change CSS Content with Js
How to Get CSS Class by Name from Stylesheet
Kendo Chart Legend:Label at Left, Color at Right
How to Zoom into a Web Page Like Ie or Firefox Do, Using Programming
How to Get Display:Table-Cell Support in Ie? Any Pure JavaScript or Jquery Workaround