There is html:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Войти в приложение</title> <link rel="stylesheet" type="text/css" href="./css/index.css"> <script src="./js/index.js"></script> </head> <body class="register-page"> <div class="register-auth"> <div class="error-1"></div> <div class="error-2"></div> <div class="register-auth-header-exit"> <div class="register-auth-title">Войти в приложение</div> </div> <form action=""> <input class="register-auth-input-error" placeholder="Заполните поле" type="text"> <input class="register-auth-input-error" placeholder="Неверный пароль" type="password"> <input class="register-auth-button-exit" type="submit" value="Войти"> </form> </div> </body> </html> 
I can not turn to the js selector:

 var el = document.querySelector('.register-auth-input-error'); console.log(el);/*Возвращает null*/ 

returns null, and I need to add a class

 el.classList.add("error"); 

if not difficult, send on the right path)

  • the script fulfills before the entire dom is loaded. It is necessary to write a script either at the end, or window.onload - Alexey Shimansky
  • querySelectorAll cannot return null, since it returns a collection, and in the absence of elements that satisfy the selector, returns an empty collection - Grundy
  • Thanks for answers. I tried to write a script at the end, and lo and behold, it all worked! - panstone

1 answer 1

Everything works fine:

 var el = document.querySelector('.register-auth-input-error'); console.log(el); el.classList.add("error"); 
 .error {border: 1px solid red; } 
 <body class="register-page"> <div class="register-auth"> <div class="error-1"></div> <div class="error-2"></div> <div class="register-auth-header-exit"> <div class="register-auth-title">Войти в приложение</div> </div> <form action=""> <input class="register-auth-input-error" placeholder="Заполните поле" type="text"> <input class="register-auth-input-error" placeholder="Неверный пароль" type="password"> <input class="register-auth-button-exit" type="submit" value="Войти"> </form> </div> </body> 

  • There was a similar problem with querySelector . There in the parameter name CSS selector should start with a dot . No point does not work. - Drakonoved