barbara
barbara

Reputation: 3201

JavaScript doesn't see a backgroundColor?

Why I can't 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 can't see a block with styles.

Upvotes: 3

Views: 45

Answers (1)

Rudie
Rudie

Reputation: 53831

That's not how element.style works. el.style only takes from the element's style attribute, so it would only see backgroundColor if it had a style="background-color: red".

You want window.getComputedStyle():

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

You can try on this page, in 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 60 fps is 16 ms, so you can do ~ 2000 getComputedStyles per frame.

Upvotes: 5

Related Questions