Replace multiple times using jQuery
attributes, image, jquery
Solution
The code works almost well, but is changes each `<img>` to the first image. Some functions work for all matched elements, like `css` or `wrap`, but some work only for the first element - those are the functions that you'd expect to return a single value - `attr`, in this case.
You should use:
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();
});
See also:
- `.attr()` - "Get the value of an attribute for the first element in the set of matched elements."
- `.each()`
Problem
I'm extremely new to jQuery and JS in general. I need the script to scan a page and replace any images classed 'rounded' with a wrapper div so I can apply rounded corners through css3. The code I've done works perfectly except if there's 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 greatly 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(); ```