Author: Stasyuk Eugene 150 Tags: , 16.12.2022

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');

		});
	})();
  1. We take it and put it in a file with scripts. (Please note that this code will only work if jquery is connected.)
  2. Then, on the page we need, we find the img tag whose image we want to expand and add the “svg” class to it

Other articles

Popup window on the site (modal window) pop-up window

Popup window on the site (modal window)

Popup window on the site (modal window)

When I was just learning the basics of development, I used to make a popup window manually. Yes, yes – instead of finding some ready-made solution, I did this thankless task 🤪. It seemed to me that there was nothing particularly complicated about it. But, only after some time of working on this issue, I […]

How to Use a Child Theme in WordPress doughter

How to Use a Child Theme in WordPress

How to Use a Child Theme in WordPress

Recently I received a request to make a budget online store with an admin panel. Of course, in this question, I decided to use WordPress in conjunction with Woocommerce. One of the offered storefront eCommerce plugin themes is Storefront. The free version, as expected, does not offer a rich selection of settings. But, nevertheless, it […]