bushdiver
bushdiver

Reputation: 771

jQuery replace background image with replace function

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"));

Upvotes: 1

Views: 459

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206038

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

Upvotes: 0

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

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"));

Upvotes: 2

Related Questions