Ad

JQuery: Replace Each Background-Image With 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/

Ad

Answer

Try

$('.imgeWrapper').find('img').attr('src','/url');
Ad
source: stackoverflow.com
Ad