How to get values of tbody element from the Table using the Table id and without giving tbody ID using javascript not Jquery
Asked Answered
C

2

5

I am looking for the elements inside the tbody of table without using the tbody Id or class. from below code i am looking for the values inside td for those who has tr classname tag.

<table id="tableId">
<thead>
</thead>
<tbody>
<tr>
value
</tr>
<tr class="className">
<td>
value
</td>
</tr>
<tr>
value
</tr>
<tr class="className">
<td>
value
</td>
</tr>
</tbody>
</table>
Charmion answered 25/4, 2017 at 13:26 Comment(1)
Use javascript querySelector - document.querySelector('#tableId > tbody > tr:nth-child(1)');Paternity
T
7
var tableId = document.getElementById('tableId');
var tBody = tableId.getElementsByTagName('tbody')[0];
var tableRow = tBody.getElementsByTagName('tr');

for (var t = 0; t < tableRow.length; t++){
    console.log(tableRow[t].innerHTML)
}
Triage answered 25/4, 2017 at 13:34 Comment(1)
can you please look this question again i made some change. I am sorry for this. @TriageCharmion
L
0

My working code is just like this

const updateTable = (urls) => {
    // Correctly select the table's tbody using the table's ID
    const tbody = document.getElementById("links").getElementsByTagName('tbody')[0];
    
    if (!tbody) {
        console.error("Table body not found!");
        return;
    }

    tbody.innerHTML = '';  // Clear previous results

    urls.forEach((url, index) => {
        const tableRow = `
            <tr>
                <td>${url.links}</td>
                <td>${url.text}</td>
                <td>${url.type}</td>
            </tr>
        `;
        tbody.insertAdjacentHTML('beforeend', tableRow);
    });
Lipfert answered 21/8 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.