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

220
Views
Focus Button by default on page load

Attempting a vanilla js solution to focus .btn-1 by default on page load.

Can't figure out why I keep getting this error : index.js:2 Uncaught TypeError: document.getElementsByClassName(...).focus is not a function at window.onload (index.js:2)

Anyone have thoughts on this please?

index.html :

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="index.css">
</head>

<body>

    <button class="btn btn-1">1</button>
    <button class="btn btn-2">2</button>
    <button class="btn btn-3">3</button>

    <script src="index.js" async defer></script>
</body>

</html>

index.css :

.btn {
  /* background-color: #4caf50; Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: block;
  font-size: 16px;
  margin: 1em;
}

.btn:hover {
  background-color: grey;
}

.btn:focus {
  background-color: blue;
}

index.js :

window.onload = function () {
  document.getElementsByClassName('btn-1').focus();
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The getElementsByClassName returns an array you can do this if you do like this

window.onload = function () {
  document.getElementsByClassName('btn-1')[0].focus();
};

or you can use querySelector instead which targets the first element on the document

window.onload = function () {
  document.querySelector('.btn-1').focus();
};
about 4 years ago · Juan Pablo Isaza Report

0

Have you tried the autofocus attribute you can give to the button elements.

Refer the link

<button type="button" autofocus>Click Me!</button>
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!