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

160
Views
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 answers
Answer question

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