Reputation: 1793
Lets say I have two divs
How do I use .find to get div1's background image, than apply that background image to div2, and replace ".jpg" with "_highlighted.jpg" ?
var div2bg = $('.div1').find('div').attr('background-image'??)//how to assigned the background image as a variable?
$('.div2').css("background-image", "url(" + div2bg + ")");
$('.div2').css("background-image").replace(".jpg", "_highlighted.jpg");
Upvotes: 0
Views: 947
Reputation: 268344
You an accomplish this with the following code:
// Get the first background image
var bg = $(".div1").css("background-image");
// Assign a modified version to another DIV
$(".div2").css("background-image", bg.replace(".jpg", "_highlighted.jpg"));
Whether or not the following is applicable to your project, you decide: I would like to point out this type of stuff is generally best handled with classes, and using jQuery methods like:
$(".div2").addClass("highlighted");
$(".div2").removeClass("highlighted");
It greatly reduces the verbosity of your scripts, and allows you to keep visual styles maintained in your CSS, rather than being partially-dependent upon values and strings within scripts.
Upvotes: 1
Reputation: 19358
Close but replace returns a string, it doesn't change the source.
I think you want this instead:
var div2bg = $('.div1').css('background-image');
$('.div2').css("background-image", div2bg.replace(".jpg", "_highlighted.jpg"));
Upvotes: 4