Note that the function used is plural getElementsByTagName
and therefore returns an array of elements instead of an element. You can change your code to assign color to element 0 which will be the first and only doing:
document.getElementsByTagName('body')[0]
Example:
var x = Math.random();
if (x < 0.5) {
document.getElementsByTagName('body')[0].style.backgroundColor = "lightgrey";
}
else {
document.getElementsByTagName('body')[0].style.backgroundColor = "dodgerblue";
}
Alternatively you can even generate a completely random color if you like, making use of rgb in color assignment in the form of:
rgb(vermelho, verde, azul)
Where each of the color parts goes from 0 to 255, being 0 empty and 255 full.
var vermelho = Math.round(Math.random()*255); //criar um numero de 0 a 255 e arredondar
var verde = Math.round(Math.random()*255);
var azul = Math.round(Math.random()*255);
document.getElementsByTagName('body')[0].style.backgroundColor = "rgb(" + vermelho + "," + verde + "," + azul + ")";
Does your latest solution work for any tag??? e.g.: Document.div.style.background...
– nelson450
@nelson450 No, just the
body
.– Woss
Thanks for the help, I’m beginner in JS
– nelson450