0

I need to edit the style attribute with jQuery. Here is what I am trying to do.

I have a div

<div style="background:url('images/image.png') no-repeat scroll 0 0 transparent;color:red;">
hello
</div>

and I need to change the background to something else like image2.png

How can I do this with jQuery?

2

2 Answers 2

3

Use .css():

$('div').css('background', 'url(images/image2.png)')

To set your entire background string, you can use a property map:

var cssObj = {
  'background-image': 'url(images/image2.png)',
  'background-repeat': 'no-repeat',
  'background-attachment': 'scroll',
  'background-position': '0 0',
  'background-color': 'transparent'
}
$('div').css(cssObj);
Sign up to request clarification or add additional context in comments.

4 Comments

He has a string there, for his background properties. Could you show him the difference between .css() and .css({});?
Thank you, and if you tell me also how to remove it it will be helpfull, or else i will make another question about that, without touching the color?
@themhz: color is a different property and will not be affected by setting the background property. I suggest to have a look at the documentation for more information/examples.
Added in using .css({}). As @FelixKling said, this will not affect the color property at all.
1
$(function(){
   var cssObj = {
      'background-image' : 'url(http://www.mousescrappers.com/forums/xperience/icons/teacups24.png)',
      'background-repeat' : 'no-repeat',      
    }
   $("div").css(cssObj);
});

The above script loads image on the document ready. Note that it loads for all Div's. So you better be more specific about the element ( use Id or class as selector)

Example http://jsfiddle.net/XsRuC/9/

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.