0

I've read many similar questions but I just find what's happening to be really weird. So I'm loading some elements into the page with an ajax call and querySelectorAll is not finding them.

So I was thinking: "It's because the elements weren't loaded into the page yet, and querySelectorAll returns a static list." So I decided to consol.log the document before calling the selector and it actually prints out the elements:

my js code

const tableBody = table.querySelector('tbody');
console.log(tableBody);
const rows = tableBody.querySelectorAll('tr');
console.log(rows);

Output on the browser's console

enter image description here

So tbody appears to have the elements before the selector is called, yet the returned array is an empty list. Furthermore, I have an await right before my ajax call that populates the page, so this code should run after, I believe.

I managed to fix it by using getElementsByClassName(), which returns a dynamic list, but I still don't understand why this way doesn't work.

Any ideas? Thx :)

  • After ajax call you should Parse it to HTML DOM, then you can call any HTML element inside it. In javascript, you can use `createElementFromHTML` – Hai Tien May 15 '22 at 04:38
  • Basically, the console is showing you a live view of your `tableBody` element. It updates in the console when the `` elements are added. My advice, don't use `console.log()` for debugging. Use the debugger instead – Phil May 15 '22 at 04:40

0 Answers0