Graphics in svg format is a fairly convenient and widely used image format. For example, in an svg with css styles, we can change its color. And as we know, we can do this procedure only if there is markup on the svg page. But what if such an image is connected to the page using the img tag. In this case, the following code will come to our aid:
(function($ = jQuery) {
$('img.svg').each(function() {
let img = jQuery(this);
let imgID = img.attr('id');
let imgClass = img.attr('class');
let imgURL = img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
let svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined') {
svg = svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined') {
svg = svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
svg = svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if (!svg.attr('viewBox') && svg.attr('height') && svg.attr('width')) {
svg.attr('viewBox', '0 0 ' + svg.attr('height') + ' ' + svg.attr('width'))
}
// Replace image with new SVG
img.replaceWith(svg);
}, 'xml');
});
})();
- We take it and put it in a file with scripts. (Please note that this code will only work if jquery is connected.)
- Then, on the page we need, we find the img tag whose image we want to expand and add the “svg” class to it