How do I link my JavaScript function to an HTML element?

I am trying to get my randomly generated number to appear in a paragraph in my HTML but I keep getting an error that I cannot set text content of null. The id is correct and where I would like it to be. What am I doing incorrectly?

function generateNumToMatch() {
    var numToMatch = (Math.floor(Math.random() * (100) + 1));
    document.getElementById("computerNumber").textContent = numToMatch;
}  
 <div class ="card-body">
    <p id ="computerNumber" class="card-text"></p>
 </div>

3 answers

  • answered 2018-10-11 19:39 Davidwestcoast

    I think the problem was in the JS, I was able to produce random numbers using this:

    var numToMatch;
    generateNumToMatch();
    function generateNumToMatch() {
        numToMatch = (Math.floor(Math.random() * (100) + 1));
    }
    document.getElementById("computerNumber").textContent = numToMatch;
    

  • answered 2018-10-11 20:35 Wigwam

    Your HTML element needs to use the onclick attribute. Add a button, and add code to it like this:

    <button onclick="generateNumToMatch()">Click me</button>
    

    The button's onClick event fires which runs your javascript code. Your javascript code will run and set the element called "computerNumber" text property to the random number you created.

    Alternatively, you can run the code once, so you do it like this:

    var numToMatch;
    numToMatch = (Math.floor(Math.random() * (100) + 1));
    document.getElementById("computerNumber").textContent = numToMatch;
    

  • answered 2018-10-11 23:22 Bigga_HD

    Triggered by an onclick event:

    function generateNumToMatch() {
        let numToMatch = (Math.floor(Math.random() * (100) + 1));
        document.getElementById("computerNumber").innerHTML = numToMatch;
    }
    <div class="card-body">
        <button onclick="generateNumToMatch()">Get a number</button>
            <p id="computerNumber"></p>
     </div>

    Triggered on a page load:

    function generateNumToMatch() {
        let numToMatch = (Math.floor(Math.random() * (100) + 1));
        document.getElementById("num").innerHTML = numToMatch;
    }
    span {
      color:red;
    }
    <body onload="generateNumToMatch()">
      <h4>Random number goes here: 
        <span id="num"></span>
      </h4>
    </body>