Search code examples
javascriptjqueryhtmlreplacebackground-image

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/


Solution

  • Try

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