Reputation: 2869
What is a good way to replace all background-images on certain elements, to be each element's own id + ".jpg"? Using jquery
Do I need to use $.each, or can I edit this to work somehow:
$(".element").css("background-image", "url(img/" + $(this).data("id") + ".jpg)");
// it sets undefined.jpg, $(this) is not the way
EDIT PS: data("id") is not a typo/mistake. I use data.id on the element
Upvotes: 0
Views: 58
Reputation: 398
You can use each() for this.
$( ".element" ).each(function( index ) {
$(this).css("background-image", "url(img/" + $(this).attr("id") + ".jpg)");
});
Upvotes: 0
Reputation: 477
It is good to use each method if there are more than one elements.
$(".element").each(function(){
$(this).css("background-image", "url(img/" + $(this).attr("id") + ".jpg)");
});
Upvotes: 0
Reputation: 2764
$('.element').each(function (index, element) {
$(element).css("background-image", "url(img/" + $(element).attr('id') + ".jpg)");
});
Upvotes: -1
Reputation: 388406
You can the setter version of .css() that takes a function as the second argument and then return the style value from that function
$(".element").css("background-image", function () {
return "url(img/" + $(this).data("id") + ".jpg)"
});
In your case this
will refer to the function's context in which you have written the code, instead you need to have a reference to the current .element
element.
Upvotes: 5