A recent requirement demanded that all the .jpg images on a page be replaced with .png’s. Here’s how to solve this requirement using jQuery
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Change Image Extensions</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#replAll").click(function() {
$('img').each(function() {
var src = $(this).attr("src");
$(this).attr("src", src.replace(/\.jpg$/i, ".png"));
});
});
});
</script>
</head>
<body>
<input id="replAll" type="button" value="Replace" /><br />
<img src="images/abc.jpg" />
<img src="images/emo.jpg" />
</body>
</html>
OUTPUT
Clicking on the ‘Replace’ button changes all .jpg’s to their .png’s counterpart. I have used different images to be able to demonstrate that the images did get changed.
Tweet
1 comment:
A better way to write it would be:
$(function() {
$("#replAll").click(function() {
$('img').attr("src", function(i, attr) {
return attr.replace(/\.jpg$/i, ".png");
});
});
});
Post a Comment