0

i have tried to give body<> a class with same name .. so that use it later to change the color of background when button is clicked .. i do not know if it from the syntax right .., any suggustions

<script>
    function ChangeColor()
    {
        var ChangeColor = document.getElementsByClassName("body");
        ChangeColor.style.background-color = "grey";
    }
</script>
treyBake
  • 6,440
  • 6
  • 26
  • 57
Hasan Othman
  • 68
  • 1
  • 10

4 Answers4

0

try this

   function ChangeColor(){
      var ChangeColor = document.getElementsByClassName("body")[0];
      ChangeColor.style.backgroundColor = "grey"; 
    }
doğukan
  • 23,073
  • 13
  • 57
  • 69
  • that was new to me with size of array ..i did not know that getElementsByClassName give collection back .. that why should choose thr first element :) .. thanks that was helpfull – Hasan Othman Feb 19 '19 at 09:18
  • you're welcome. please accept the my answer also. – doğukan Feb 19 '19 at 09:19
0

getElementsByClass name returns an array, you choose the first item

function changeColor(){ 
  var ChangeColor = document.getElementsByClassName("body")[0]; 
  ChangeColor.style.backgroundColor = "grey"; 
}

then call the function

 changeColor();

that should work...

Ande Caleb
  • 1,163
  • 1
  • 14
  • 35
0

You need to make two changes

First you need to pass index when using document.getElementsByClassName since it is a collection. Second for inline styling using javascript rename background-color to backgroundColor

function changeColor() {
  var changeColor = document.getElementsByClassName("body")[0];
  changeColor.style.backgroundColor = "grey";
}

changeColor()
<body class='body'>
</body>
brk
  • 48,835
  • 10
  • 56
  • 78
0

getElementsByClassName returns a array.

So you should do like :

ChangeColor[0].style.background-color = "grey"

I believe you are not using any framework that could make that. In that case i would suggest to add a id to the element and use getElementById. In that case it will return a single element