3

I have a div of images.. eg:

<div class="image-container">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p1.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p2.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p3.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p4.jpg" class="image-style" typeof="foaf:Image">
</div>

and I want to use jQuery to go through each image and make it a div then asign the image as a background image... like this:

<div class="image-container">
        <div style="background-image:url(http://mysite.com/images/portfolio/p1.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p2.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p3.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p4.jpg)"><span>image</span></div>
</div>

I know how to do this for one but not sure the best way to go through all the images in my parent div (image-container) and convert them.

Any help will be very much appreciated. C

Cybercampbell
  • 2,486
  • 11
  • 48
  • 75

3 Answers3

3

You can use replaceWith method:

$('.image-container img').replaceWith(function(i, v){
    return $('<div/>', {
        style: 'background-image: url('+this.src+')',
        html: '<span>image</span>'
    })
})

http://jsfiddle.net/FD9gV/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

Oh well to do through each you can always do

$('div.image-container img').each( function(i,o){
    // function for one of your img tags
    // which is accessible easily via $(o), e.g.
    $(o).replaceWith('<div style="background:url(' + $(o).attr('src')+')"><span>image</span></div>');

});
Cimbali
  • 11,012
  • 1
  • 39
  • 68
1

Try this please; :) http://jsfiddle.net/x5HhV/

jquery change background-image

Hope this fits the cause :)

API: http://api.jquery.com/replaceWith/

code

$("div.image-container > img").each(function(index) {
    index = index + 1
    $(this).replaceWith('<div style="background-image:url(http://mysite.com/images/portfolio/p' + index + '.jpg)"><span>image</span></div>');

    alert(index + ' HTML is now changed to => ' + $("div.image-container").html());

});

​
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77