DEV Community

GiandoDev
GiandoDev

Posted on

Toggle Password Visibility

Alt Text

Top comments (2)

Collapse
 
aminnairi profile image
Amin

Hi there, really great demo of how to do it. Congrats!

You should account for all cases of the return value of document.querySelector, especially in the case the selector is wrong, or the element has a different selector, etc... You won't be notified when this happens because your application live in the client-side and it will just throw an error, nothing much.

Instead, by adding a quick check, you could send an asynchronous request to a web service like Sentry, or to an API of yours to send you an email in case this kind of thing happen. I know this may be overkill but even if you don't have these kind of tools, it's always good to check and at least describe clearly what happend (maybe this should not block the rest of the script for instance, unlike an error).

"use strict";

const myInput = document.querySelector("#my-input");

if (myInput instanceof HTMLInputElement) {
  // Do something with my input
} else {
  // Do something in case my input is not found
}

// Continue the script because not having my input is not a critical error

I added the use of HTMLInputElement to be really sure I'm dealing with an HTML input, because checking that this is an HTML element is not enough. Divs for instance do not have a value property of a focus method. So it will throw an error as well.

Collapse
 
giandodev profile image
GiandoDev

Cool 😎 thanks 🙏