change div background colour to random in javascript

Here's how you can change the background color of a div to a random color using JavaScript:

index.tsx
// Get the div you want to change the background color of
const myDiv = document.getElementById('my-div');

// Function to generate a random color
function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

// Set the background color of the div to a random color
myDiv.style.backgroundColor = getRandomColor();
446 chars
16 lines

This code generates a random color using the getRandomColor function and sets the background color of the myDiv element to the generated color. You can trigger this code when the user interacts with the page, or use setInterval to change the color automatically over time.

gistlibby LogSnag