0

Heyo! I'm using getElementById() to modify the href of a favicon to a random number that is associated to a picture. However, every time I do this, the variable I try to assign it to is null What am I doing wrong?

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript">


    var number = Math.floor((Math.random() * 5) + 1);

    var ico = number + ".ico"

    document.getElementById("favicon").href = ico <!-- should change the icon -->

</script>
<title>Cool Server People!</title>
<link rel="stylesheet" href="style.css">
<link id="favicon" rel="shortcut icon"  href="1.ico" /> <!-- should edit this part -->

</head>
<body>
<div class="header">
    <h1>Cool Server People</h1>
</div>

<div class="space">

</div>  

<div class="blog">

    <a href="test-post.html" class="post">Blog Post</a>
    <p>asdfdasdfasdfasdfa</p>

</div>

  • 1
    I think it has to do with the position of your script tag. Inline scripts execute as soon as they show up, so the link tag doesn't exist yet. Try moving the script to the bottom of the page (right above the end `

    ` tag.

    – solarc Sep 25 '17 at 23:41

1 Answers1

1
  1. Please place your JS code before
  2. This error is because you are trying to get an element earlier than DOM Content is Loaded. That's it!

<!DOCTYPE html>

<html>
<head>
    <title>Cool Server People!</title>
    <link rel="stylesheet" href="style.css">
    <link id="favicon" rel="shortcut icon"  href="1.ico" /> <!-- should edit this part -->

</head>
<body>
<div class="header">
    <h1>Cool Server People</h1>
</div>

<div class="space">

</div>

<div class="blog">

    <a href="test-post.html" class="post">Blog Post</a>
    <p>asdfdasdfasdfasdfa</p>

    <script type="text/javascript">
        
        var number = Math.floor((Math.random() * 5) + 1);
        var ico = number + ".ico";
        document.getElementById("favicon").href = ico; <!-- should change the icon -->

    </script>

</div>
zhuravlyov
  • 483
  • 2
  • 10