In this lesson we learn how can we manipulate Css by using Java script and Dom.
In this example we selecting id of div = foo with method of document.getElementById and set it into a var divFoo. After than we create a new var and set var style by using divFoo.style method, than we modify css properties with style method. First we change text color into blue, change background yellow, set a border with color black and than align the text into center.
This is nice but all code are very messy right? So we can use an another method by create a class into style body and than dynamically add by Java script, let see:
In above example we create first a new class name = "modifyClass" than we put it into style portion and give to all same properties like color, background, text-align and border radius. After than we just join this new class with divFoo. Finally we get same result with very nice and simple code. We can also replace this class. We also can set multiple classes as divFoo.className = "modifyClass anotherClass anotherOneClass"; just by giving one space in two or more classes. We can replace classes by using this replace method : divFoo.className = divFoo.className.replace(" anotherClass ", ""); Here empty semi colons replace anotherClass into empty class. By using this anotherClass can't able to work.
There is a one more special method classList and it's work in all new major browser's. ClassList method is use for add a class, remove the class, toggle the class for doing class functionality on or off.
Get Computed Style is default window method : window.getComputedStyle() use for computing the base values of particular element and its work with getPropertyValue() object for finding the base value. For example if we use this as :
var divFoo = document.getElementById("foo");