How come changing elements' attribute values in vanilla JS and jQuery sometimes don't work similarly? One scenario is the experiment I created, where whenever the "Show password" button is being clicked, the password field's type attribute value is supposed to change into text when it is password, and vice versa. It worked successfully in vanilla JS but not in jQuery. In jQuery, the attribute value changes to text, but when I want to change it back to password, it won't work. Why does such issue occur?
Vanilla JS
document.querySelector('.show-password').onclick = function() {
if(document.querySelector('#password').type == 'password') {
document.querySelector('#password').type = 'text';
} else {
document.querySelector('#password').type = 'password';
}
}
jQuery
$('.show-password').click(function() {
if($('#password').attr('type', 'password')) {
$('#password').attr('type', 'text');
} else {
$('#password').attr('type', 'password');
}
});
if($('#password').attr('type') == 'password'). Rubberduck-debug your code. There’s no reason 7 lines of code should fail.