Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SVGO plugin to convert the `id` attribute of an element to a `class` attribute with the same value.
// This SVGO plugin converts the `id` attribute on an element into a `class` attribute with the same value.
// To use it, you'll need to disable the `cleanupIDs` plugin, otherwise you won't have any `id` attribute to replace :)
'use strict';
exports.type = 'perItem';
exports.active = true;
exports.description = 'convert id attribute to class, using the same value';
exports.fn = function(item) {
if (item.isElem() && item.hasAttr('id')) {
var id = item.attr('id')
item.addAttr({
name: 'class',
value: id.value,
prefix: '',
local: 'class'
})
item.removeAttr('id')
}
}
@tylertrotter

This comment has been minimized.

Copy link

tylertrotter commented Jun 13, 2019

Thanks! This is exactly what I need. However, I'm not seeing this work on svg and g elements. Do you know why that might be?

@tylertrotter

This comment has been minimized.

Copy link

tylertrotter commented Jun 13, 2019

Contrary to what I thought before, it is unrelated to the kind of element. It seems that preexisting classes are messing this up. It works if right before line 15 I add:

if (!item.hasAttr('class')) {
  item.addAttr({
    name: 'class',
    value: '',
    prefix: '',
    local: 'class'
  });
}

Here is the svg I'm testing on:

<svg id="download" 
	xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
	<defs>
		<style>.cls-1,.cls-2{fill:none;stroke:#000;stroke-width:2px;}.cls-2{stroke-linecap:square;}</style>
	</defs>
	<title>download</title>
	<g id="download">
		<line id="download_ground" class="cls-1" y1="15.15" x2="16" y2="15.15"/>
		<g id="download_arrow">
			<polyline class="cls-2" points="3 6 8 11 13 6"/>
			<line class="cls-1" x1="8" x2="8" y2="11"/>
		</g>
	</g>
</svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.