CSSStyleDeclaration Test
by Rodrigo
HTML
<div class="styleTest">
<h1>Playing with CSSStyleDeclaration</h1>
<button id="button">
Target Element
</button>
<hr/>
<h2>Results</h2>
<div id="results">
Test
</div>
</div>
CSS
.styleTest {
color: darkgrey;
font-family: Verdana, Arial, Tahoma, Serif;
}
h1, h2 {
font-size: 20px;
}
#button {
margin: 20px;
padding: 10px;
color: darkblue;
background-color: white;
cursor: pointer;
}
#results {
margin-bottom: 100px;
}
JavaScript
const win = document.defaultView || window
const element = document.getElementById('button')
// Loop over computed styles
const styles = win.getComputedStyle(element, '')
console.log(styles)
// String variable to hold styling for each element
let elementStyle = ''
for (let key = 0; key < styles.length; key++) {
// Check if style should be processed
if (styles.getPropertyValue(styles[key])) {
elementStyle += styles[key] + ':' + styles.getPropertyValue(styles[key]) + ';'
}
}
document.getElementById('results').innerText = `Styles length: ${styles.length}, Element Style: ${elementStyle}`