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

121
Views
Problem of using element.addEventListen("keydown", function) over document.addEventListener("keydown", function)

I have a NodeList of button elements numbers. I want each of the elements listen to keydown event in respective to their own textContent.

When I use document.addEventHandlers("keydown", function), it works fine.

Method 1:

document.addEventListener("keydown", (e)=>{
numbers.forEach(number=>{
    if (number.textContent === e.key){
        addNumber(number)
    }})})

However, it stops working when I use this instead:

Method 2:

numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
    if (number.textContent === e.key){
        addNumber(number);
    }}))

The first method seems not efficient to me since it has to make comparison to every items in numbers everytime "keydown" is fired. Can anyone tell me why the method 2 don't work as method 1?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

If the problem is the performance, you can map your numbers in a map/dictionary with their textContent as a key and the number object as a value. Then:

document.addEventListener("keydown", (e) => {
    var number = numbersByKey[e.Key];
    if (number)
        addNumber(number);
})
about 4 years ago · Santiago Gelvez Report

0

    document.addEventListener("keydown", (e)=>{
    numbers.forEach(number=>{
        if (number.textContent === e.key){
             addNumber(number)
        }})})

In the above code, you are adding a keydown listener for the document itself, so whenever you press a key on the keyboard, this event is fired.

     numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
         if (number.textContent === e.key){
             addNumber(number);
         }}))

In this code, you are adding a keydown listener to the individual element, so only if the element is focused the keydown event will be fired for that element

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!