Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda