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

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

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 Denunciar

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