3

What I am trying to do is change the background-image of a div, but only if the background-image url matches a certain url.

Here is the HTML:

<div class="test" style="background-image: url("/background1.png");">

Now what I've tried is this:

if ($('.test').css('background-image') === 'url(/background1.png)') {
    $('.test').css("background-image", "url(/background2.png)");
}

I know that the replace works, because if I remove the first line it updates all the background images for me, but I can't seem to get the first line to work.

4 Answers 4

3

You could use something like this

 var bg = $(".test").css('background-image');
 bg = bg.replace('url("','').replace('")','');


 if (bg === '/background1.png') {
    $('.test').css("background-image", "url(/background2.png)");
 }

Example fiddle: https://jsfiddle.net/bpv4Lggv/19/

Sign up to request clarification or add additional context in comments.

Comments

0

.prop() might get you where you need to be.

http://www.w3schools.com/jquery/html_prop.asp

http://api.jquery.com/prop/

Comments

0

Use filter to get all the div with class test and matches background image (url(/background1.png))

var filtered = $('.test').filter(function(test){
  return $(test).css('background-image') === 'url(/background1.png)';
});
//change filtered DOM only, with the new image background
$(filtered).css("background-image", "url(/background2.png)"); }

Comments

0

I'm not familiar with JQuery but I think this was what you were asking for(in plain JavaScript)?

  if(element.style.backgroundImage == 'url("imagePathHere")'){
 // your code }

It's probably of little use now, but I was stuck trying to find a solution for a while until I console logged it and realized what my problem was, so maybe it can help someone else now😅

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.