Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace image with div and set image to background

Tags:

html

jquery

css

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

like image 232
Cybercampbell Avatar asked Mar 06 '26 21:03

Cybercampbell


1 Answers

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/

like image 73
undefined Avatar answered Mar 08 '26 11:03

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!