I am new to JS. I was trying to make a button which will change the BG color of the HTML page. This is HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/index.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btn btn-outline-secondary">Click Me!</button>
</body>
</html>
and here is the JS:
const button = document.querySelector('button');
const body = document.querySelector('body');
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple'];
body.style.backgroundColor = 'violet';
button.addEventListener('click', changeBackground);
function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length);
body.style.backgroundColor = colors[colorIndex];
}
this code is not working and it is constantly giving error on console
index.js:5 Uncaught TypeError: Cannot read property 'style' of null