1

How to do the following if the img is in the background property instead of src ?

this.src = this.src.replace("_1","_2");

css:

#someimg {  
    background:url('someimg_1.jpg');
}

Something like:

$('#someimg').css.('background-image',
    $(this).css('background-image').replace("_1","_2"));

2 Answers 2

2

It's a lot better to define classes for these different backgrounds and just add and remove the classes, instead of this fragile way of doing it, however, here is how it could be done,

var backGroundImage = $('#someimg').css('background-image');
$('#someimg').css('background-image', backGroundImage.replace("_1","_2"));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this works perfect =] - not sure what you meant about the classes, with potentially 100s of images to change to, classes might not be practical in my case..
if you have 100s of images then I guess what ur doing is fine! glad I can help :)
0

LIVE DEMO

var src2 = $('#someimg').attr('src').replace('_1', '_2');
$('#someimg').attr( 'src', src2 );

Or if you prefer you can do it this way:

var $omeimg = $('#someimg');
$omeimg.attr('src', $omeimg.attr('src').replace('_1', '_2') );

which is the most similar to what you was up to, just in your example you had 2 tiny errors:

$('#someimg').css.('background-image',  $(this).css('background-image').replace("_1","_2"));
//               ^---- this dot         ^^^^^^^---- and this undefined

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.