Modifying Element Style


In this lesson we learn how can we manipulate Css by using Java script and Dom.

Let see an Example:

Modifying Element

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:


className

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.

Class List

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.


class list

Get Computed Style

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");
alert(getComputedStyle(divFoo).getPropertyValue("color"));
Than its return rgb value of color of divFoo. This function is work in all new update or major browser's but if we want to use this functionality in legacy browsers like Internet explore 8 or below than we can use this function currentStyle : .This return color name and we can use it as : divFoo.currentStyle["color"];

If we want to run these functions together for every browser than we can create a function for all new or old browsers. This is the best example of cross browser event handling.

FunctionCompute

Wconcert India © 2015   ·   All Rights Reserved

Free Web Hosting