change background colour onclick

First time poster.

I am trying to change the background colour after clicking a button. I have tried a few different code types and what seems to be consistent is that the array doesn’t get iterated properly.

Please Help

var color = ["red", "green", "blue"];
var i = 0;
document.querySelector("button").addEventListener("click", function() {
  i = i < color.length ? ++i : 0;
  document.querySelector("body").style.background = color[i];
})
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

button {
  position: absolute;
  top: 50%;
  left: 50%;
  cursor: pointer;
}

body {
  background-color: blue;
}
<button>Click me to change background colour.</button>

Answer

Be careful to load your javascript script after the button in your HTML code, because otherwise the querySelector will not find it!

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Background Colour Change</title>
    <link rel="stylesheet" href="new1.css">
</head>
<body>
    <button>Click me to change background colour.</button>
</body> 
<script src="new1.js"></script>