I’m working entirely with javascript, and webpack generates the HTML file after I run the build.
Here are the different modules of my code:
index.js
import { renderLayout } from './layout.js';
import { generateDialog } from './dialog.js';
import './style.css';
renderLayout();
const btnAddItem = document.querySelector('button#addItem');
btnAddItem.addEventListener('click', () => { generateDialog(); });
layout.js
// some code
const div2 = document.createElement('div');
const titleDisplays = document.createElement('div');
div2.appendChild(titleDisplays);
// some more code
function renderLayout() {
document.body.appendChild(div2);
}
export {renderLayout};
dialog.js
import * as myFn from './list.js'
const dialog = document.createElement('dialog');
const submit = document.createElement('button');
submit.type = 'submit';
submit.value = 'default';
submit.id = 'confirmBtn';
submit.innerHTML = 'Confirm';
// some more code
function generateDialog() {
document.body.appendChild(dialog);
dialog.showModal();
}
submit.addEventListener('click', event => {
dialog.close();
newList(input.value); // input.value is the value inside the variable 'value' that points to a text input field
updateUI();
})
export { generateDialog };
list.js
export const titleDisplays = document.querySelector('div.sidebar div');
export let lists = []
export let listItems = []
export function newList(list) {
localStorage.setItem(list, [])
localStorage.setItem(Math.round((localStorage.length + 1) / 2), list);
}
export function emptyUI() {
while (titleDisplays.firstChild != undefined) {
titleDisplays.removeChild(titleDisplays.firstChild);
}
}
The code works completely fine in its entirety except for the emptyUI() function, which returns a ‘cannot read properties of null’ error, indicating that the titleDisplays variable is null, or not detected by the DOM or something, and I can’t understand why and how to fix it.
2
Answers
First check for existence of
titleDisplays
and only after that fortitleDisplays.firstChild
:Though it’s not clear why you’re using a while loop here.
Is it really needed?
You can, for example, check periodically for existence of element with
setInterval
reference this.