0

I'm adding a script that adds random background images to pages, like so:

<script type="text/javascript">
var totalCount = 25;
function addBackground()
{
  var num = Math.ceil( Math.random() * totalCount );
  document.body.background = 'images/'+num+'.png';
  document.body.style.backgroundSize = "contain";
}
</script>

The complication is, I now need to only add backgrounds to pages that have a specific class (not an id) added to their html element. (I don't have access to change the way this works).

I've tried using getElementsByClassName, but I seem to keep getting Undefined back. What's the correct way to do this?

Thanks!

Wwiggins
  • 1
  • 2

1 Answers1

0

Get element on page undefined which potentially means when the code get executed the DOM is not ready. If you are not using jQuery check out $(document).ready equivalent without jQuery.

Put your logic into the ready function to make sure the element(s) is rendered at the time your logic run.

Community
  • 1
  • 1
X.Creates
  • 11,800
  • 7
  • 58
  • 98