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

83
Views
why btn.addEventListener is not a function. i am stuck in this problem and couldn't find any solution .anyone can help me?

** I am learning Dom manipulation and it's my second day... how can I make it as a function that will generate random index of color which I already stored in my array. **

const btn = document.getElementsByClassName("btn");
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>

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

0

the getElementsByClassName return an array of elements (cf doc).

to get the first element you should either get the first element of the array document.getElementsByClassName("btn")[0]; or add an id to the button and get it with the document.getElementById('myButton') function

const btn = document.getElementsByClassName("btn")[0];
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>

about 4 years ago · Juan Pablo Isaza Report

0

getElementsByClassName will return an array like object of dom elements matching the class. You need to select the entry in this array you want to target :

const btn = document.getElementsByClassName("btn")[0];

see here for details

about 4 years ago · Juan Pablo Isaza Report

0

getElementsByClassName returns an array, not a single DOM object. You can try adding an id to the element and use getElementById

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!