Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
eventlistener can't access variable outside function

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');
    });
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Gelvez Relatório

0

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);
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda