Mitchell Andrew Abbott
Mitchell Andrew Abbott

Reputation: 805

jQuery: Replace each Background-Image with <img> tags leaving sources unchanged

How would I replace every background image with the class name:

backgroundPNGAcontain

with a div (class name imgWrapper) and image having the same url source?

I'm very close. This is my code:

$( ".backgroundPNGAcontain" ).html( "<div class='imgWrapper'><img></div>" );

$( ".backgroundPNGAcontain" ).each(function() {
  var url = $( this ).css('background-image');
  url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
  $(".imgWrapper>img").attr("src", url);
  $( this ).css( "background-image", "none" );
});

It's just that $(".imgWrapper>img").attr("src", url); doesn't change the source by matching every image correctly, instead it finds the last background image and sets every image to that.

Here's a fiddle: https://jsfiddle.net/gd29wLu5/

Upvotes: 0

Views: 157

Answers (2)

DumbCoder7
DumbCoder7

Reputation: 252

Your code is replacing all images under imgWrapper with the same attribute. Instead of $(".imgWrapper>img").attr("src", url); try $(this).children("img").attr("src",url);

Upvotes: 1

Tajammul Ghafoor
Tajammul Ghafoor

Reputation: 47

Try

$('.imgeWrapper').find('img').attr('src','/url');

Upvotes: 1

Related Questions