I am writing a function that toggles two divs onclick. I have 2 functions that displays an api json data as a table and graph (formatGraph and formatTable).
i have created two different divs and appended the formatGraph and formatTable functions to those divs. Then created a mainDiv to wrap the two divs.
I have an if statement that checks for when to show or hide the divs. I am calling the formatData function somewhere in my fetch call while rendering my result. I have a css file with the following code:
.displayTable {
display: block;
}
.displayGraph{
display: none;
}
But I am currently getting undefined and
Uncaught TypeError: Cannot read properties of null (reading 'style')
at HTMLButtonElement.
Any idea what I am missing, or how I can go about this? Here's my function:
const formatData = (response) => {
const mainDiv = document.createElement("div");
const div1= document.createElement("div");
div1.classList.add("displayTable");
div1.appendChild(formatTable(response));
mainDiv.appendChild(div1)
const div2 = document.createElement("div");
div2.classList.add("displayGraph");
div2.appendChild(formatGraph(response));
mainDiv.appendChild(div2)
viewTable.addEventListener("click", function() {
if(document.querySelector('.displayTable').style.display === "none") {
document.querySelector('.displayGraph').style.display = 'none';
document.querySelector('.displayTable').style.display = 'block';
}
else{
document.querySelector('.displayTable').style.display === "none"
document.querySelector('.displayGraph').style.display = 'block';
}
})
};
undefinedand you are trying to access thestyleproperty on it, Probably your element is not loaded in the browser, The line no error pointing to, that is undefined, if you can console logdocument.querySelector('<your-selector>'), you will see undefinedtype="module"to your HTML script tag so that the JS loads after your HTML