xjs get css 2026-06-06
xjs get css
write a simple js that gets css from element id #basic and output it into element id #output.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Get CSS from Element</title> <style> #basic { width: 300px; height: 200px; background-color: #4CAF50; color: white; padding: 20px; margin: 20px; border: 3px solid #333; font-family: Arial, sans-serif; } </style> </head> <body> <div id="basic"> This is the element whose CSS we will read. </div> <button onclick="getCSS()">Get CSS of #basic</button> <pre id="output" style="background:#f4f4f4; padding:15px; margin-top:20px; white-space:pre-wrap;"></pre> <script> function getCSS() { const elem = document.getElementById('basic'); const output = document.getElementById('output'); // Get computed styles const styles = window.getComputedStyle(elem); let cssText = `/* Computed styles for #basic */\n\n`; // Loop through all styles for (let i = 0; i < styles.length; i++) { const prop = styles[i]; const value = styles.getPropertyValue(prop); if (value) { cssText += `${prop}: ${value};\n`; } } output.textContent = cssText; } </script> </body> </html>
How to use:
- Copy the whole code above into an
.htmlfile. - Open it in your browser.
- Click the button → it will read all computed CSS from
#basicand show it nicely in#output.
Even simpler version (just the JS function):
function getCSS() { const elem = document.getElementById('basic'); const output = document.getElementById('output'); const styles = window.getComputedStyle(elem); let css = ''; for (let prop of styles) { const value = styles.getPropertyValue(prop); if (value) css += `${prop}: ${value};\n`; } output.textContent = css; }
Just call getCSS() whenever you want (e.g. on button click).