Get Property Value in CSS style
Description
The following code shows how to explore CSS Properties Programmatically in Javascript.
Example
<!-- ww w.jav a 2 s . c o m-->
<!DOCTYPE HTML>
<html>
<head>
<style title="core styles">
p {
color: white;
background-color: gray;
padding: 5px;
}
</style>
</head>
<body>
<p id="block1">
This is a test.
</p>
<div id="placeholder"></div>
<script>
var placeholder = document.getElementById("placeholder");
displayStyles();
function displayStyles() {
var newElem = document.createElement("pre");
newElem.setAttribute("border", "1");
var style = document.styleSheets[0].cssRules[0].style;
for ( var i = 0; i < style.length; i++) {
newElem.innerHTML+=style[i]+" "+style.getPropertyValue(style[i]);
}
placeholder.appendChild(newElem);
}
</script>
</body>
</html>
Example 2
<!-- www . j av a 2 s . c o m-->
<!DOCTYPE HTML>
<html>
<head>
<style title="core styles">
p {
color: white;
border: medium double black;
background-color: gray;
padding-top: 5px;
}
</style>
</head>
<body>
<p id="block1">This is a test.</p>
<div>
<button id="pressme">Press Me</button>
</div>
<div id="placeholder"></div>
<script>
var placeholder = document.getElementById("placeholder");
displayStyles();
document.getElementById("pressme").onclick = function() {
var styleDeclr = document.styleSheets[0].cssRules[0].style;
styleDeclr.setProperty("background-color", "lightgray");
styleDeclr.setProperty("padding-top", "20px");
styleDeclr.setProperty("color", "black");
displayStyles();
}
function displayStyles() {
if (placeholder.hasChildNodes()) {
var childCount = placeholder.childNodes.length;
for (var i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
var newElem = document.createElement("pre");
newElem.setAttribute("border", "1");
var style = document.styleSheets[0].cssRules[0].style;
newElem.innerHTML += "border" + style.getPropertyValue("border");
newElem.innerHTML += "color" + style.getPropertyValue("color");
newElem.innerHTML += "padding-top" + style.getPropertyValue("padding-top");
newElem.innerHTML += "background-color" + style.getPropertyValue("background-color");
placeholder.appendChild(newElem);
}
</script>
</body>
</html>