Skip to content

Instantly share code, notes, and snippets.

@richhauck
Created December 10, 2017 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richhauck/5ac4ee8d3ac6a3aec5ae7bb8045bf185 to your computer and use it in GitHub Desktop.
Save richhauck/5ac4ee8d3ac6a3aec5ae7bb8045bf185 to your computer and use it in GitHub Desktop.
SVG Image Replacement
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SVG Image Replacement</title>
<style>
.holder{
width: 100px;
margin: 0 auto;
}
.svg:hover{
cursor: pointer;
fill: red;
}
</style>
</head>
<body>
<div class="holder">
<img class="svg" src="bars.svg" alt="bars">
<img class="svg" src="bars.svg" alt="bars">
<img class="svg" src="bars.svg" alt="bars">
<img class="svg" src="bars.svg" alt="bars">
</div>
<script>
let svgs = document.getElementsByClassName('svg')
for(let i = 0; i < svgs.length; i++){
let target = svgs[i];
let ajax = new XMLHttpRequest();
ajax.open('GET', target.src, true);
ajax.send();
ajax.onload = function(e) {
let response = ajax.response;
// parse string response as SVG
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(response, 'image/svg+xml');
let svg = xmlDoc.childNodes[0];
// apply id and class attributes
svg.id = target.id;
svg.classList = target.classList;
var s = new XMLSerializer();
var str = s.serializeToString(svg);
// replace target img with embedded svg
target.parentNode.replaceChild(svg, target)
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment