I'm relatively new to JS so it might be blatantly obvious so I do apologize
I've written a small function that generates a random hexcode to apply against a html class, but it just won't initialize.
<!DOCTYPE html>
</head>
<body onload="get_random_color()">
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<script language="javascript">
var rand = document.getElementsByClassName("para");
function get_random_color(){
var letters ='0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15 )];
}
return color;
rand.style.backgroundColor = get_random_color();
}
</script>
</body>
Any insights or help would be greatly appreciated, thanks
J
You have many issue with the code.
body onload calls get_random_color, which correctly generates the color, but you then have a return which prevents it from being assigned to the style in the following line.rand is assigned not one element but a collection of elements. See the documentation of getElementsByClassName. Even if your return wasn't there, the collection does not have a style property. You have to set the style on each element using a for loop.get_random_color function, the rand.style.backgroundColor = get_random_color(); calls itself - if return wasn't there, you'd get a stack overflow because the method would call itself over and over.rand is misnamed - it should be paragraphs or something like that.Gather up the paragraphs by class using querySelectorAll, iterate over them and apply a new color to each by calling the function.
const paras = document.querySelectorAll('.para');
paras.forEach(para => para.style.color = get_random_color());
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>