Rotate an SRC image into a background image in jQuery

How to set src image using jQuery

I want to do the opposite of what this jQuery snippet does. I need some code that will turn

<img src="images/filename.jpg"> 

to become

 <div class="imageBox" style="background:url(images/filename.jpg)"></div> 

I searched up and down, trying to find something that would do it, but it turned out empty. I am not a jQuery guru, so I would appreciate any help anyone could offer. Thanks

+4
source share
1 answer
 $("img").each(function(i, elem) { var img = $(elem); var div = $("<div />").css({ background: "url(" + img.attr("src") + ") no-repeat", width: img.width() + "px", height: img.height() + "px" }); img.replaceWith(div); }); 

Live demo

+6
source

All Articles