JavaScript doesn't see backgroundColor?

Why can't I see my style?

    <style>
        .style{
            background-color: pink;
            top: 50px;
            left: 50px;
        }
    </style>
    <script>
        window.onload = function () {
            console.log(document.querySelector('.style').style.backgroundColor);
        }
    </script>
    </head>
    <body><div class="style">A</div></body>

      

Seams that JS cannot see the styled block.

+3


source to share


1 answer


It doesn't work element.style

. el.style

takes only the element's style attribute, so it only sees backgroundColor

if it has style="background-color: red"

.

You want window.getComputedStyle()

:

var el = document.querySelector('.style');
var bg = getComputedStyle(el).backgroundColor;

      

You can try this page on the console:

getComputedStyle(document.querySelector('pre')).backgroundColor

      



Speed:

el = document.querySelector('pre');
console.time('getComputedStyle');
for (i=0; i<1000; i++) c = getComputedStyle(el).backgroundColor;
console.timeEnd('getComputedStyle');

      

returns:

getComputedStyle: 9.120ms

      

1 frame at 60fps is 16ms, so you can do ~ 2000 getComputedStyle

per frame.

+5


source







All Articles