0

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');
    }
});
1
  • 3
    It should be if($('#password').attr('type') == 'password'). Rubberduck-debug your code. There’s no reason 7 lines of code should fail. Commented Oct 13, 2016 at 2:24

1 Answer 1

6

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.