How to change CSS properties of html elements using javascript or jquery

How to change CSS

to javascript

.

I am using jQuery-ui Dialog

and I want to change the style DIV

from javascript.

thank

+1


source to share


4 answers


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

Anyway, if you want to add styles to elements, you need to use a function css

that has several options.

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

      

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

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

      

The first method is easier if you are installing several things at once.



If you want to check which property is currently set, you must use a variation of the second option, just omit the value.

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

      

Would make var color

be red

if you already set it above eg.

You can also add and remove classes by doing something like

$(selector).addClass(class_name);
$(selector).removeClass(class_name);

      

+8


source


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 only want to change some of the attributes, you can always find the element using

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

      

and then change the style of the attached color to



div.style.color = 'Green';

      

Instead, your red text will appear in green.

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

div.className = 'bar';

      

causing the div to now use the class bar, which makes your blue green text blue.

+2


source


There are several ways to manipulate element styles using the jQuery framework. Check out the documentation related to CSS and changing attributes:

+1


source


Try it. This is jquery code.

 $("myDiv").css({"color":"red","display":"block"})

      

If you are using vanila javacript try this.

var myDiv = document,getElementById("myDiv");

myDiv.style.display = "block";

myDiv.style.color = "red";

      

0


source







All Articles