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

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

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 Denunciar

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 Denunciar

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 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