Created
October 10, 2018 10:17
-
-
Save bomberstudios/848827b37bed38ca0aae5fe2bbd0843a to your computer and use it in GitHub Desktop.
SVGO plugin to convert the `id` attribute of an element to a `class` attribute with the same value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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') | |
} | |
} |
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
Thanks! This is exactly what I need. However, I'm not seeing this work on
svg
andg
elements. Do you know why that might be?