Change the color style in JavaScript
Description
The following code shows how to change the color style.
Example
<!-- w ww.j a va 2 s . c om-->
<!DOCTYPE HTML>
<html>
<head>
<style title="core styles">
#block1 {
color: white;
border: thick solid black;
background-color: gray;
}
p {
border: medium double black;
background-color: lightgray;
}
</style>
</head>
<body>
<p id="block1">This is a test.</p>
<p id="block2" style="border: medium dashed blue; color: red; padding: 2px">
This is a test.
</p>
<button id="pressme">Press Me</button>
<div id="placeholder"></div>
<script>
var placeholder = document.getElementById("placeholder");
displayStyles();
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].cssRules.item(1).style.paddingTop = "10px";
document.styleSheets[0].cssRules.item(1).style.paddingRight = "12px";
document.styleSheets[0].cssRules.item(1).style.paddingLeft = "5px";
document.styleSheets[0].cssRules.item(1).style.paddingBottom = "5px";
displayStyles();
}
function displayStyles() {
if (placeholder.hasChildNodes()) {
var childCount = placeholder.childNodes.length;
for ( var i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
displayStyleProperties(document.styleSheets[0].cssRules.item(1).style);
displayStyleProperties(document.getElementById("block2").style);
}
function displayStyleProperties(style) {
var newElem = document.createElement("pre");
newElem.setAttribute("border", "1");
newElem.innerHTML += style.border + " ";
newElem.innerHTML += style.color + " ";
newElem.innerHTML += style.padding + " ";
newElem.innerHTML += style.paddingTop + " ";
placeholder.appendChild(newElem);
}
</script>
</body>
</html>
The code above generates the following result.
Javascript Tutorial Color
Change background color in JavaScript
Change background for a paragraph element i...
Change color for a paragraph element in mou...
Change color in JavaScript
Change element color by setting the color s...
Get and set node background color in JavaSc...
Get background Color in JavaScript
Remove CSS background property with event.t...
Remove CSS color property with event.target...
Update bacground color recursively in JavaS...
Change background color in JavaScript
Change background for a paragraph element i...
Change color for a paragraph element in mou...
Change color in JavaScript
Change element color by setting the color s...
Change the color style in JavaScript
Get Color in JavaScriptGet and set node background color in JavaSc...
Get background Color in JavaScript
Remove CSS background property with event.t...
Remove CSS color property with event.target...
Update bacground color recursively in JavaS...