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

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

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

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