Intentar una solución vanilla js para enfocar .btn-1 de forma predeterminada en la carga de la página.
No puedo entender por qué sigo recibiendo este error: index.js:2 Uncaught TypeError: document.getElementsByClassName(...).focus is not a function at window.onload (index.js:2)
¿Alguien tiene pensamientos sobre esto, por favor?
índice.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>índice.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; }índice.js:
window.onload = function () { document.getElementsByClassName('btn-1').focus(); };getElementsByClassName devuelve una matriz que puede hacer esto si le gusta esto
window.onload = function () { document.getElementsByClassName('btn-1')[0].focus(); };o puede usar querySelector en su lugar, que apunta al primer elemento en el documento
window.onload = function () { document.querySelector('.btn-1').focus(); };