views:

466

answers:

3

Hi Guys,

How can I change CSS from javascripts. Im using JQUERY (Dialog) and I want to change the style of a DIV from javascript.

Thanks

+1  A: 

There are a couple of ways to manipulate elements styles using the jQuery framework. Take a look through the documentation related to CSS and changing attributes:

cLFlaVA
+8  A: 

Check out the jQuery documentation. If you want anything it will be there.

Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.

$(selector).css(properties);  // option 1
$(selector).css(name, value); // option 2

So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do

$("div#mydiv").css({'background-color' : 'red'}); // option 1
$("div#mydiv").css('background-color','red');     // option 2

The first way is easier if you're setting multiple things at once.

If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.

var color = $("div#mydiv").css('background-color');

Would make the var color be red if you already set it above, for example.

You can also add and remove classes, doing something like

$(selector).addClass(class_name);
$(selector).removeClass(class_name);
Paolo Bergantino
+2  A: 

This answer works even without jQuery.

So you have something like this:

<style type="text/css">
    .foo { color: Red; }
    .bar { color: Blue; }
</style>
<div class="foo" id="redtext"> some red text here </div>

If you wish to change just some attributes, you can always find the element using

var div = document.getElementById('redtext');

function and then change the attached color style by

div.style.color = 'Green';

Making your red text appear in green instead.

If you want to change the class defined for the div to another style class, you can do:

div.className = 'bar';

making the div now use class bar, which makes your previously green text blue.

Tuminoid