Script to dynamically create a 3 columns per n rows from a list

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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>
</code>
<code>@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> </code>
@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>

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.

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

0

HTML is executed from top to bottom. So, as with other programming languages.

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var tableau = document.getElementById('tableau');
</code>
<code>var tableau = document.getElementById('tableau'); </code>
var tableau = document.getElementById('tableau');

before reaching:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><div id="tableau"></div>
</code>
<code><div id="tableau"></div> </code>
<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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><body>
<div id="tableau"></div>
<script>...</script>
</body>
</code>
<code><body> <div id="tableau"></div> <script>...</script> </body> </code>
<body>
    <div id="tableau"></div>
    <script>...</script>
</body>

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật