5

I can't figure out how I can change an attribute in a CSS Class. Right now I add a style to that specific div, but what I want is for the attribute in the CSS class to be changed, and not just overridden by the new style attribute.

An example:

.example{background-color:blue}

<div class="example">example</div>

So how can I then change the background-color in the .example CSS and not just by overriding it like this:

<div class="example" style="background-color:blue">example</div>

I have tried a lot of things, but I cant figure it out. I have tried .attr() and .css(), but am I missing something.

2
  • 4
    Should work with just .css("background-color", "blue"); yes? Commented Jun 26, 2013 at 13:47
  • can you show the jquery code that you are using? Commented Jun 26, 2013 at 15:22

3 Answers 3

4

You can't change the actual CSS of the class (well you can, but it's extremely difficult and against practice) -- but you can change it for everything that is applied to that class now:

$('.example').css('background-color', 'blue');

What you can do however, is re-apply that CSS whenever a new element of your type is generated. For example, after calling an AJAX script that retrieves data from another file:

$('#blah').load('script.php', function() {
    $('.example').css('background-color', 'blue');
});

You can also have an interval that re-applies on all elements for you, but performance wise this is not recommended:

setInterval(function() {
    $('.example').css('background-color', 'blue');
}, 100);

My advice to you would be to find another way to mark your changes, like a second class and use that class to inflict the changes on your elements.

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

Comments

0

What you want isn't possible, but something like this might be better.

body.blueTheme .example { background-color: blue; }
body.redTheme .example { background-color: red; }

Now instead of changing the color in your event handler, change the class of the body.

Comments

0

Dynamically changing style sheets is normally a bad idea, unless you're intending to implement complete re-theming.

It would be generally better to find some other way to mark the elements so that they acquire a different style, but if you must do this, you can dynamically change which stylesheets are loaded.

Put an id on a <style> element that links to an external CSS file:

<link id="dynCss" rel="stylesheet" type="text/css" href="..." />

and then put the two different variations of the style in two different CSS files.

and then you can use:

document.getElementById('dynCss').href = ...

or

$('#dynCss).attr('href', ...);

which will then load (and apply) the new styles in the new URL.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.