4

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

Community
  • 1
  • 1
jbwharris
  • 710
  • 1
  • 10
  • 30

1 Answers1

9
$("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
  • 81,538
  • 47
  • 180
  • 227
  • +1 - Although you forgot the class - `
    ` instead of just `
    ` should do the job nicely.
    – gnarf Oct 27 '10 at 20:32
  • What is this function doing? I just don't see how this bit of code is outputting an inline background-image – jbwharris Oct 28 '10 at 13:58
  • @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 Oct 28 '10 at 14:51
  • 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. – jbwharris Oct 28 '10 at 15:22
  • @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 Oct 28 '10 at 16:12