Replace multiple times with jQuery

I am extremely new to jQuery and JS in general. I need a script to scan the page and replace any images classified as "rounded" with a div wrapper, so I can apply rounded corners via css3. The code I made works fine if there are more than 1 image on the page, it just returns the first image 3 times instead of 3 separate images.

Code below - any help is appreciated.

var imageWrap = jQuery("img.rounded").attr("src");
var imageWrapWidth = jQuery("img.rounded").attr("width");
var imageWrapHeight = jQuery("img.rounded").attr("height");
var imageWrapAlt = jQuery("img.rounded").attr("alt");
jQuery("img.rounded").wrap("<div class='image-wrapper'><p></p>" + "</div>");

jQuery(".image-wrapper").css({'background' : 'transparent url('+imageWrap+') no-repeat 0 0','width':imageWrapWidth,'height':imageWrapHeight}  );
jQuery(".image-wrapper p").text(imageWrapAlt);
jQuery('img.rounded').hide();
+3
source share
5 answers

, <img> . , css wrap, - , - attr, .

:

jQuery("img.rounded").each(function(){
  var img = jQuery(this);
  var imageWrap = img.attr("src");
  var imageWrapWidth = img.attr("width");
  var imageWrapHeight = img.attr("height");
  var imageWrapAlt = img.attr("alt");

  //next, the '.image-wrapper' selector is also wrong - it selects all new wraps.
  var wrapper = jQuery("<div class='image-wrapper'><p></p>" + "</div>")
          .css(
               {'background' : 'transparent url('+imageWrap+') no-repeat 0 0',
                'width':imageWrapWidth,'height':imageWrapHeight})
         .text(imageWrapAlt);
  img.wrap(wrapper).hide();
});

. :

+4

each . -

jQuery("img.rounded").each(function(){
    //$(this) will get you the current image element
    // save the reference to a variable so that each time you won't have 
    //     to access the DOM element.
    var currElem = $(this); 
    var imgSrc = currElem.attr("src");
});
+1

"attr" , .

0

.each(), , - .

0

thanks to everyone - the first poster, and I will return to invaluable help. I ended up with this and it works great - thanks again

jQuery("img.rounded").each(function(){
    var img = jQuery(this);
    var imageWrap = img.attr("src");
    var imageWrapWidth = img.attr("width");
    var imageWrapHeight = img.attr("height");
    var imageWrapAlt = img.attr("alt");
    jQuery(this).wrap("<div class='image-wrapper'>" + "<p></p></div>");
    jQuery(this).parent().parent().css({'background' : 'transparent url('+imageWrap+') no-repeat 0 0','width':imageWrapWidth,'height':imageWrapHeight});
    jQuery(this).parent().text(imageWrapAlt);
    jQuery(this).hide();
});
0
source

Source: https://habr.com/ru/post/1734011/


All Articles