the read element was appended to another div container element by the submit eventlistener. but I can't access the read element when trying to attach it to another event listener outside the function. Any idea how to fix this?
function add() {
read = document.createElement('div');
read.textContent = 'Read';
read.classList.add('read');
card.appendChild(read);
}
submit.addEventListener('click', add);
read.addEventListener("click", () => {
read.classList.toggle('unread');
});
You code is not really correct. I would suggest:
let read = null;
function add() {
if (read) return;
read = document.createElement('div');
read.textContent = 'Read';
read.classList.add('read');
card.appendChild(read);
read.addEventListener("click", () => {
read.classList.toggle('unread');
});
}
submit.addEventListener('click', add);
Although without a context on what you are trying to achieve it's going to be difficult.
BTW: no, variables that are declared inside a function are scoped, you cant access them from outside
The read element's eventListener isn't activated, because first if you click on the submit element the read element is an element.
Solution:
function add() {
read = document.createElement('div');
read.textContent = 'Read';
read.classList.add('read');
card.appendChild(read);
read.addEventListener("click", () => {
read.classList.toggle('unread');
});
}
submit.addEventListener('click', add);