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

138
Views
Adding class to multiple elements with querying selector

I'm trying to cut down on my verbose classList.add('lorem') calls. I can easily add the same class to multiple created elements like so:

const loremDiv = document.createElement('div'), ipsumDiv = document.createElement('div')

loremDiv.classList.add('hi')
ipsumDiv.classList.add('hi')

But when I try to add the class via a single forEach like so:

[loremDiv,ipsumDiv].forEach((el) => {
    el.classList.add('hi')
}

I get the following error: TypeError: Cannot read properties of undefined (reading 'forEach')

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As others have mentioned, you are missing vital semi-colons. Both Felix and Pointy make valid points. There is really no need to omit semi-colons. It may look more hip and modern, but it will bite you down the road and cause cryptic errors like this.

Fails

The document.createElement call returns an element, but since you did not include a semi-colon, it runs into the next line like so:

document.createElement('div')[loremDiv, ipsumDiv]

Since you did not terminate the ipsumDiv assignment, the interpreter is complaining that it was not assigned already.


As for the forEach((el) => el.classList.add('hi')) call, Array.prototype.forEach returns nothing, so you are calling loremDiv on an undefined object.

forEach((el) => el.classList.add('hi'))[loremDiv, ipsumDiv]

const 
  loremDiv = document.createElement('div'),
  ipsumDiv = document.createElement('div') // Missing semi-colon!
  
// "Uncaught ReferenceError: Cannot access 'ipsumDiv' before initialization"

[loremDiv, ipsumDiv].forEach((el) => el.classList.add('hi')) // Missing semi-colon!

// "Uncaught TypeError: Cannot read properties of undefined (reading '#<HTMLDivElement>')"

[loremDiv, ipsumDiv].forEach((el) => document.body.append(el)) // Optional semi-colon
.hi:before { content: "HI!" }

Working

const 
  loremDiv = document.createElement('div'),
  ipsumDiv = document.createElement('div'); // Semi-colon required
  
[loremDiv, ipsumDiv].forEach((el) => el.classList.add('hi')); // Semi-colon required

[loremDiv, ipsumDiv].forEach((el) => document.body.append(el)); // Why not add one?
.hi:before { content: "HI!" }

about 4 years ago · Juan Pablo Isaza 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!