Adding random numbers to column

Hi,
I’m new to JavaScript and only got a 2 hours class who didn’t have many examples, so I need help.

I got a table with 5 columns and I want to associate a random number to each column, doesn’t matter if it changes every refresh. Here’s what I tried.
HTML:

 <tbody id="tableau" onload="identifRandom()">
        <tr>
            <td class="identifiantRandom"> </td>
            <td>Gingerade</td>
            <td>1</td>
            <td>Paul Stasny</td>
             <td>Big Brother</td>
        </tr>
        <tr>
            <td class="identifiantRandom"> </td>
            <td>The bug...</td>
            <td>2</td>
            <td>Adam Bernstein</td>
            <td>Small Brother</td>
        </tr>

Javascript:

function identifRandom() {
    let columnNumber = document.querySelectorAll('identifiantRandom');
    for (let i = 0; i < columnNumber.length; i++) {
       let nombreIdentifiant = Math.floor((Math.random() * 100) + 1);
       console.log(nombreIdentifiant);
       return nombreIdentifiant
    }
}

I know I’m missing something.

Thanks for your help!

Hello!

Two things.

First, the onload attribute doesn’t mean that all the content has been loaded. In this case would mean that the <tbody> tag was loaded, but the <td>s might not, hence when the function identifRandom is triggered there might not be any content to iterate. To fix this, if not using jQuery, for example, You should include the script at the bottom of the page, just before the closing body tag:

   <!-- Other HTML content -->

   <script src="my-script.js"></script>
</body>

And in my-script.js:

function myFunction() {
  // The code of myFunction
}

myFunction();

And second, You have some errors:

function identifRandom() {
    // *.querySelector, *.querySelectorAll take as parameter a CSS selector.
    // hence here You're missing a dot. The class is .identifiantRandom.
    let columnNumber = document.querySelectorAll('.identifiantRandom'); // This is a list of HTML (DOM) elements
    for (let i = 0; i < columnNumber.length; i++) {
       // But here, You're not accessing any of the DOM elements.
       let nombreIdentifiant = Math.floor((Math.random() * 100) + 1);
       console.log(nombreIdentifiant);
       // Instead of the following:
       // return nombreIdentifiant
       // Do this:
       columnNumber[i].innerText = nombreIdentifiant;
    }
}

It should work after this changes :slight_smile:

1 Like