Adding data to cell by td number of table with javascript

Hello,

Adds data to table cells without any problem with the following code

for(i = 1; i <= 24; i++)
	document.getElementsByTagName('td').item(i).firstChild.data = data('elem'+i,r);

When I use this the second table is affected
That’s why I want to use tableid

<table id="tableid">
    <tr>
        <th>&nbsp;</th>
        <th>&nbsp;</th>
        <th>&nbsp;</th>
        <th>&nbsp;</th>
        <th>&nbsp;</th>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>9</td>
        <td>10</td>
        <td>11</td>
        <td>12</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>13</td>
        <td>14</td>
        <td>15</td>
        <td>16</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>17</td>
        <td>18</td>
        <td>19</td>
        <td>20</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td>21</td>
        <td>22</td>
        <td>23</td>
        <td>24</td>
    </tr>
    <tr>
        <th>&nbsp;</th>
        <td colspan="4">&nbsp;</td>
    </tr>
</table>

It shifts the order when I use it as below

for(i = 1; i <= 24; i++)
document.querySelectorAll('#tableid td').item(i).firstChild.data = data('elem'+i,r);

Can you help me

Thank you

Rather than use document.getElementsByTagName(), use element.getElementsByTagName(), by first referencing the correct table element by its id. See the example at this link - Element.getElementsByTagName() - Web APIs | MDN

1 Like

I couldn’t do it again because my knowledge is insufficient, can you help a little more?

As below worked for now, I hope it’s correct
Thank you

document.getElementById("tableid").getElementsByTagName("td").item(i).firstChild.data

Sponsor our Newsletter | Privacy Policy | Terms of Service