1

I have an assignment in javascript that changes the font of the tag on button click but I'm getting this error. I don't think there is anything wrong in my code.

  <button onclick="myFunction()">Set font</button>
    <script type = "text/javascript">
    function myFunction() {
        document.getElementsByTagName("body").style.fontFamily = "Times New Roman, Times, serif";
    }

1 Answers1

2

document.getElementsByTagName("body") does not return a single element, but an array of items.

You can fix your code by accessing the array by index:

document.getElementsByTagName("body")[0].style.fontFamily

Edit: On a side note as Ivar has mentioned in his comment: the body can be accessed explicitly with document.body.

code-gorilla
  • 2,231
  • 1
  • 6
  • 21