tags:

views:

49

answers:

1

http://stackoverflow.com/questions/2183347/how-to-set-the-image-src-using-jquery

I am looking to do the opposite of what this jQuery snippet does. I need a bit of code that will turn

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

to become

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

I've searched up and down trying to find something that will do this but have come up empty. I'm no jQuery guru, so I would appreciate any help someone could offer. Thanks

+2  A: 
$("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

Josh Stodola
+1 - Although you forgot the class - `<div class='imageBox' />` instead of just `<div />` should do the job nicely.
gnarf
What is this function doing? I just don't see how this bit of code is outputting an inline background-image
jamEs
@James It loops through each `img` tag, creates a `div` and sets the background image to the `src` of the `img`, then it replaces the `img` with the `div`. Want a demo?
Josh Stodola
Sure. I've been trying to get it to work in a big, complicated template, so maybe seeing it working on it's own would help.
jamEs
@James Answer updated to include link to a live demo with three images. It replaces them with `div` and sets the inner HTML of the `div` to the `alt` attribute of the `img`.
Josh Stodola
Thanks for the demo, greatly appreciated.
jamEs