Get and set style in plain text in Javascript

Description

We can use cssText to get and set style in plain text in Javascript.

Example


<!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();<!--from   ww w .j a  v  a  2 s .  co  m-->
    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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window