Author: Stasyuk Eugene 109 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

How to Translate a WordPress Theme to Another Language перевод

How to Translate a WordPress Theme to Another Language

How to Translate a WordPress Theme to Another Language

While working on creating a WordPress theme, we often come across such inscriptions as “upload more, author, tags”, etc. For example, as in my blog: It’s good when the site is in one language. Then you don’t really need to do anything with them. But what to do when the site is multilingual. If the […]

Date range in WP_Query – output posts by meta_query wordpress

Date range in WP_Query – output posts by meta_query

Date range in WP_Query – output posts by meta_query

WP_Query class is one of the WordPress tools that helps to display posts according to the required parameters: categories, sorting, date range, etc. The list of parameters is pretty decent. You can read more about them in the documentation here: https://developer.wordpress.org/reference/classes/wp_query/ . Some parameters are quite extensive and sometimes it’s much easier to understand them […]