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

3 Answers 3

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/

0
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());

});

​
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>');

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.