// code from above wrapped into a function
replaceSVG();
// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#CCC');
}, function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#3A3A3A');
});
/*
* Replace all SVG images with inline SVG
*/
document.querySelectorAll('img.svg').forEach(function(img){
var imgID = img.id;
var imgClass = img.className;
var imgURL = img.src;
fetch(imgURL).then(function(response) {
return response.text();
}).then(function(text){
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
// Get the SVG tag, ignore the rest
var svg = xmlDoc.getElementsByTagName('svg')[0];
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
svg.setAttribute('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
svg.setAttribute('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
svg.removeAttribute('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!svg.getAttribute('viewBox') && svg.getAttribute('height') && svg.getAttribute('width')) {
svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
}
// Replace image with new SVG
img.parentNode.replaceChild(svg, img);
});
});
public static function print_svg($file){
$iconfile = new \DOMDocument();
$iconfile->load($file);
$tag = $iconfile->saveHTML($iconfile->getElementsByTagName('svg')[0]);
return $tag;
}
Note that `#img` is the id of the `svg` tag inside svg file. Also note `xlink:href` has been deprecated instead you should use `href` or use can use both to support older browser versions.
Another way of doing it: [https://css-tricks.com/cascading-svg-fill-color/][1]
[1]: https://css-tricks.com/cascading-svg-fill-color/
let img = document.querySelector('img[class^="YourClassName"]');
let imgURL = img.src;
fetch(imgURL)
.then(response => response.text())
.then(text => {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, 'text/xml');
let svg = xmlDoc.getElementsByTagName('svg')[0];
let paths = xmlDoc.getElementsByTagName('path');
// access individual path elements directly
let leftShape = paths[0];
leftShape.setAttribute('fill', '#4F4F4F');
// or find specific color
const pathsArr = Array.from(paths);
let skirtShape = pathsArr.find(path => path.getAttribute('fill') === '#F038A5');
skirtShape.setAttribute('fill', '#0078D6');
// Replace old SVG with colorized SVG
// positioning and alignment is left untouched
let base64Str = btoa(new XMLSerializer().serializeToString(svg));
img.src = 'data:image/svg+xml;base64, ' + base64Str;
});