Skip to main content

Add Classes to SVG

Overrides the class attribute in the outer most <svg> element, omitting duplicates or null classes if found in your configuration.

caution

If there is no class attribute to begin with, it will be added. However, if the there were already classes assigned, these are removed and replaced with the classes configured in this plugin.

If you have a standalone SVG, this is not an optimization and will increase the size of the SVG document. This plugin is only relevant when considering multiple SVGs that may be inlined a parent document.

By adding classes, if the parent document is aware, you can share styles across all inlined SVG elements.

Usage

svgo.config.js
module.exports = {
plugins: [
"addClassesToSVGElement"
]
}

Parameters

classNames

Adds the specified class names to the outer most <svg> element.

className

Adds the specified class name to the outer most <svg> element. If classNames is specified, this is ignored.

Demo

Live Editor
const svg = `
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox=" 0 0  150 100 " width="150">
  <!-- Created with love! -->
  <defs>
    <ellipse cx="50" cy="50.0" rx="50.00" ry="auto" fill="black" id="circle"/>
  </defs>
  <g>
    <use href="#circle" transform="skewX(16)"/>
    <rect id="useless" width="0" height="0" fill="#ff0000"/>
  </g>
</svg>
`;

const svgoConfig = {
  js2svg: { indent: 2, pretty: true },
  plugins: [
    "addClassesToSVGElement"
  ]
}

render(<SvgoPreview svg={svg} svgoConfig={svgoConfig}/>);
Result
Loading...

Implementation