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

162
Visualizações
Why event listener doesnt work with class

I want to add an event listener to my input class to do some validation.

So here is my code:

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = document.getElementsByClassName("inputs");

input.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
})
</script>

</body>
</html>

So if I do that with id, the code works perfectly but it doesn't work with the class. SO do you know why?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

getElementsByClassName returns an HTMLCollection. You have to add the event listener to the first item in it.

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = document.getElementsByClassName("inputs")[0];

elements.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
})
</script>

</body>
</html>

If you want to add the event listener to each item, loop through the HTMLCollection:

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = [...document.getElementsByClassName("inputs")];

elements.forEach(e => e.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
}))
</script>

</body>
</html>

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