Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda