Skip to content
Advertisement

Can not get the element [closed]

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:

<table class="table table-striped" >
    <tbody>
        
    </tbody>
</table>

And my JS

    data_base.body.appendChild(tr);


        const data_base = {
            body: document.getElementsByTagName("tbody")[0],
        }

(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

const tbody = document.querySelector('tbody');

so instead of

data_base.body.appendChild(tr);

use :

tbody.appendChild(tr);

by the way u can replace

    const tr = document.createElement("tr");

    const td_id = document.createElement("td");

    const td_name = document.createElement("td");

    const image = document.createElement("img");

    const td_image = document.createElement("td");

    td_image.appendChild(image);

    const td_price = document.createElement("td");

    const td_operation = document.createElement("td");

    const operation = document.createElement("button");

    td_operation.appendChild(operation);

    td_id.textContent = i;

    td_name.textContent = data_base.naming;

    image.src = data_base.url;

    image.alt = "Couldn't load image";

    td_price.textContent = data_base.price;

    operation.setAttribute("click", "sitDown()");



    tr.appendChild(td_id);
    tr.appendChild(td_name);
    tr.appendChild(td_image);
    tr.appendChild(td_price);
    tr.appendChild(td_operation);
    data_base.body.appendChild(tr);

with

const tr = document.createElement("tr");

tr.innerHTML = `
<td>${i}</td>
<td>${data_base.naming}</td>
<td><img src="${data_base.url}" alt="Couldn't load image"></td>
<td>${data_base.price}</td>
<td><button></button></td>
`;

data_base.body.append(tr);

to make your code more readable

and dont add an event listener as attribute as u did here

operation.setAttribute("click", "sitDown()");
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement