Get a live CSS value with JavaScript Using getComputedStyle()
The element.style property only give the access to those CSS attribute whose set through the element.style property.
So the value of those CSS attribute which is not set by the element.style property will be only get by the getComputedStyle() method.
getComputedStyle() method will gives the live value of the all CSS attribute.
Read CSS value through the element.style
element.style property will return the empty string(“”) for all those CSS attribute value which is not set through the it.
var h2Head = document.getElementById("h2Head"); var padding = h2Head.style.padding; alert("Padding: " + padding);
Check the above live demo, If you run that demo you will get empty string(“”) because we are trying to access the padding of the element which is not set through the element.style property.
getComputedStyle(element, pseudo)
So for the reading live CSS attribute value JavaScript provides the getComputedStyle() method.
getComputedStyle() method has the 2 argument.
element:
The element to get a styling for
pseudo:
A pseudo-selector like ‘hover’ or null if not needed.
Second pseudo argument is optional.
All the modern browser and IE browser supports the getComputedStyle() method excepts IE < 9.
var h2Head = document.getElementById("h2Head"); var padding = getComputedStyle(h2Head).padding alert("Padding: " + padding);
Click on the above link to check the live demo, If you run the above program you will get the real time value of the padding of the element is the 20px.