I try to display elements of my database on my web page after loading it.
I fetch these elements using AJAX and it works fine.
The problem is when I try to assign container (myTable) to put there my elements (elementsOfDataBase).
I get an error 'JavaScript Uncaught TypeError: myTable is null' in my console.
I use DOM getElementById. ID 'my-Table' is unique.
Any idea what I'm doing wrong?
myJs.js
$.ajax({
type: 'GET',
url: 'myUrl/',
success: function(response){
console.log('success')
let elementsOfDataBase = response.table
const myTable = document.getElementById("my-Table");
elementsOfDataBase.map(item => {
const div = document.createElement('div')
div.innerHTML += item.fields.item
div.innerHTML += '<br>'
myTable.appendChild(div);
})
},
error: function (error){
console.log('error')
},
})
home.html
<div id="my-Table"></div>
IMO you try to access the table before it's rendered. Try
$(document).ready(function(){
//Your code
});