Categories
JavaScript Answers

How to set the background-color of a D3.js svg with JavaScript?

Spread the love

To set the background-color of a D3.js svg with JavaScript, we can call attr to set the class attribute.

For instance, we write

const svg = d3
  .select("body")
  .append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .attr("class", "graph-svg-component");

to select the body element with select.

And then we call append to append the svg as the last child of the body element.

Next, we call attr to set the class attribute to the graph-svg-component class.

And then we add

.graph-svg-component {
  background-color: green;
}

into the CSS file to apply styles for the class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *