Access the css text from cssText in JavaScript

Description

The following code shows how to access the css text from cssText.

Example


<!--  w  w w . j  av  a 2 s  . co  m-->

<!DOCTYPE HTML>
<html>
<body>
<p id="block1" style="color: white; background-color: gray">
This is a test.
</p>
<button id="pressme">Press Me</button>
<div id="placeholder"></div>
<script>
var placeholder = document.getElementById("placeholder");
var targetElem = document.getElementById("block1");
displayStyle();
document.getElementById("pressme").onclick = function() {
targetElem.style.cssText = "color:black";
displayStyle();
}
function displayStyle() {
if (placeholder.hasChildNodes()) {
placeholder.removeChild(placeholder.firstChild);
}
var newElem = document.createElement("pre");
newElem.innerHTML += targetElem.style.cssText;
placeholder.appendChild(newElem);
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Access the css text from cssText in JavaScript