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');
}
});
Because if($('#password').attr('type', 'password'))
is not asking if the type attribute is 'password'. It is setting type=password and returning a jQuery object to the if statement.
When .attr() is used with only one parameter , it gets that attribute from the selected element, so yo can do it using $("#password").attr("type") == "password"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.