Hello so when I try to get the tbody element in JavaScript I get the error that it is null But whenever I use the same method to get the element but in a different file it works perfectly.
I have tried getting the element by id and class but nothing seems to be working.
Here is my HTML:
JavaScript
x
6
1
<table class="table table-striped" >
2
<tbody>
3
4
</tbody>
5
</table>
6
And my JS
JavaScript
1
7
1
data_base.body.appendChild(tr);
2
3
4
const data_base = {
5
body: document.getElementsByTagName("tbody")[0],
6
}
7
(UPDATE the problem was solved by adding the script to the bottom of the file)
Advertisement
Answer
this is how u can get ur tbody element
JavaScript
1
2
1
const tbody = document.querySelector('tbody');
2
so instead of
JavaScript
1
2
1
data_base.body.appendChild(tr);
2
use :
JavaScript
1
2
1
tbody.appendChild(tr);
2
by the way u can replace
JavaScript
1
41
41
1
const tr = document.createElement("tr");
2
3
const td_id = document.createElement("td");
4
5
const td_name = document.createElement("td");
6
7
const image = document.createElement("img");
8
9
const td_image = document.createElement("td");
10
11
td_image.appendChild(image);
12
13
const td_price = document.createElement("td");
14
15
const td_operation = document.createElement("td");
16
17
const operation = document.createElement("button");
18
19
td_operation.appendChild(operation);
20
21
td_id.textContent = i;
22
23
td_name.textContent = data_base.naming;
24
25
image.src = data_base.url;
26
27
image.alt = "Couldn't load image";
28
29
td_price.textContent = data_base.price;
30
31
operation.setAttribute("click", "sitDown()");
32
33
34
35
tr.appendChild(td_id);
36
tr.appendChild(td_name);
37
tr.appendChild(td_image);
38
tr.appendChild(td_price);
39
tr.appendChild(td_operation);
40
data_base.body.appendChild(tr);
41
with
JavaScript
1
12
12
1
const tr = document.createElement("tr");
2
3
tr.innerHTML = `
4
<td>${i}</td>
5
<td>${data_base.naming}</td>
6
<td><img src="${data_base.url}" alt="Couldn't load image"></td>
7
<td>${data_base.price}</td>
8
<td><button></button></td>
9
`;
10
11
data_base.body.append(tr);
12
to make your code more readable
and dont add an event listener as attribute as u did here
JavaScript
1
2
1
operation.setAttribute("click", "sitDown()");
2