0

There is just a red div. Nothing else. It does not do anything else.

When I log it to the console (as below) it has no style.backgroundColor. Yet I can successfully change the background color from console.

Why doesn't the original element logged in the console have a backgroundColor I can read?

Jsfiddle: https://jsfiddle.net/32ohL51d/5/

    const target = document.getElementsByTagName("div")[0];
    console.log(target); // shows the correct element but it doesn't have a .style.backgroundColor

  // however if I go to console and run target.style.backgroundColor = 'white'; it works!

  // let's check if we're waiting for the DOM to get loaded or something, 
  // so we run the log 10 times, 3 seconds apart:

    for (let i = 0; i < 10; i++) {
        setTimeout( () => {
            console.log(target.style.backgroundColor);
        }, 3000)
    } // returns empty string 10 times
<style>
    div { background-color: #f00; }
</style>
<div></div>

I can change it with target.style.backgroundColor = 'white'; though. Why?

ACJ
  • 13
  • 4
  • 2
    Because [`style` gives you the inline styles](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) and these elements don't have any (would look like `
    ` otherwise). Maybe you are looking for [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) instead.
    – CherryDT Oct 09 '22 at 13:07
  • That sounds right. Let me try it. Thanks – ACJ Oct 09 '22 at 13:08

0 Answers0