skip to Main Content

I want to change the background colour of the body element. When I tried with the first, it won’t work. But when I tried with the second, it worked perfectly. I want to know the reason.

let x = document.getElementsByTagName("BODY")[0].style.backgroundColor

function change() { x = "red"; }

let x = document.getElementsByTagName("BODY")[0]

function change() { x.style.backgroundColor = "red"; }

2

Answers


  1. In your firts example, you’re assigning the background color of the to the variable x but modifying x doesn’t affect the element because it simply reassigns x, without updating the actual style of the page.

    Login or Signup to reply.
  2. // we instantiate the variable from the element “id”.
    let body = document.getElementById( "body" );
    
    function change() { 
       body.style.backgroundColor = "red"; 
    }
    #intern {
        background: lightblue;
        width: 50px;
        height: 30px;
    }
    <body id="body">
       <div id="intern" type="button" onClick=change()>
       </div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search