skip to Main Content

I’m coding a MVC app with ASP .NET 8.0 framework and following code should retrieve a List from my controller to create a 3 columns per n rows table in my view. It run well till the last row:
tableau.appendChild(tbl);

Where I get the error:

Uncaught TypeError: Cannot read properties of null (reading ‘appendChild’)

I didn’t find a way to create my table using the foreach loop so I’m using the for loop with javascript.

@model List<ViewListTable>
<head>
  <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
  <script type="text/javascript">
    function f() {
      var myArray = [];
      @foreach(var d in Model) {
        @: myArray.push("@d.Name");
      }

      var cptData = myArray.length;
      var tableau = document.getElementById('tableau');
      var tbl     = document.createElement("table");
      var x       = 0;

      for (var i = 0; i < cptData / 3; i++) {
        var tr = document.createElement('tr');
        for (j = 0; j < 3; j++) {
          var td = document.createElement('td');
          if (x < cptData) {
            var a        = document.createElement('a');
            var el_span  = document.createElement('span');
            var linkText = document.createTextNode(myArray[x]);
            var tab      = myArray[x];

            //console.log(tab);
            el_span.setAttribute('style', 'color: #07C');
            a.setAttribute('href', "'" + tab + "'");
            a.setAttribute('class', 'button');
            a.title = "Éditer les données de la table:";
            a.appendChild(linkText);
            el_span.appendChild(a);
            td.appendChild(el_span);
          };
          x += 1;
          tr.appendChild(td)
        };
        tbl.appendChild(tr);
      }
      tableau.appendChild(tbl);
    }
    f();
  </script>
</head>
<body>
  <div id="tableau"></div> 
</body>

image

image

2

Answers


  1. I had a test in my side and I added console.info(tbl);console.info(tableau); before tableau.appendChild(tbl);, then I found that tableau is null and this is the reason for the error you shared.

    enter image description here

    The solution is moving the <script> from <head> to <body>.

    enter image description here

    Login or Signup to reply.
  2. HTML is executed from top to bottom, so, as with other programming languages.

    First, you are trying to get element with ID tableau defined in document

    var tableau = document.getElementById('tableau');
    

    before reaching

    <div id="tableau"></div>
    

    so it returns null.

    Solution is simple, move getting the element AFTER its declaration in HTML. So just move entire script element at the bottom:

    <body>
      <div id="tableau"></div>
      <script>...</script>
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search