The idea is, I want to access any cell and set properties or values. The first option works, but to work with it, it makes no sense.
When launching the second option, an error occurs that the table is empty and the code does not work any further. Why? Scope or something else? I searched Google, but could not find an answer.
I try to do this through closures, I just started teaching them, practicing them. I will improve the code. For now, I need to understand what the problem is. How should my code work?
- Call the function, set the row (rows1) where we will take the cell.
Get the table. (After all, the table is not empty, but why an error)?
var table = document.getElementById('tableCinema');- We receive collections.
- Then through the method I get the element of the array.
Did I write it correctly so that these steps were carried out? If there are errors, write what is wrong. Thank.
<table id="tableCinema" style="border-collapse: collapse;" border="1"> <tr> <th>Type</th> <th>Name</th> <th>Time</th> </tr> <tr> <td>1</td><td >*</td><td >*</td> </tr> <tr> <td>2</td><td >*</td><td >*</td> </tr> <tr> <td >3</td><td >*</td><td >*</td> </tr> <tr> <td>4</td><td >*</td><td >*</td> </tr> </table> <button onclick="addObj()">add</button> // ************************************************ *****
var arrMovies = [ {name: "Simpsons", time: "14:20"}, {name: "Zootopia", time: "18:30"}, {name: "Avatar", time: "19:00"}, {name: "Boss", time: "11:40"} ]; function addObj() { var table = document.getElementById('tableCinema'); var trsTable = table.getElementsByTagName('tr'); var tdsTable = trsTable[2].getElementsByTagName('td'); function addValue(arrElem) { tdsTable[1].innerHtml = arrMovies[arrElem].name; tdsTable[2].innerHtml = arrMovies[arrElem].time; } tdsTable[1].innerHTML = arrMovies[3].name; } //Это второй вариант. function addObj2(rows1){ var table = document.getElementById('tableCinema'); //Uncaught TypeError: Cannot read property 'getElementsByTagName' of null //TypeError: table is null var trsTable = table.getElementsByTagName('tr'); var tdsTable = trsTable[rows1].getElementsByTagName('td'); function addValue (arrElem) { tdsTable[1].innerHtml = arrMovies[arrElem].name; tdsTable[2].innerHtml = arrMovies[arrElem].time; } console.log(tdsTable[1].innerHTML); } var rows2 = addObj2(2); rows2(1);