How to change CSS properties of html elements using javascript or jquery
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);
source to share
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.
source to share