Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!