admin管理员组

文章数量:1315981

I would like to change the HTML 'input' element 'type' attribute, from type="password" to type="text".

I am aware that it would be easier to find element by ID but not every page has the same id for the password input. How do I target the password inputs and change their inner value to a type of text.

I have this few lines of JavaScript code:

a=document.getElementsByTagName("input"); 
a.setAttribute(type,text);

I would like to change the HTML 'input' element 'type' attribute, from type="password" to type="text".

I am aware that it would be easier to find element by ID but not every page has the same id for the password input. How do I target the password inputs and change their inner value to a type of text.

I have this few lines of JavaScript code:

a=document.getElementsByTagName("input"); 
a.setAttribute(type,text);
Share Improve this question edited Sep 10, 2014 at 21:13 A K asked Sep 10, 2014 at 20:55 A KA K 974 silver badges13 bronze badges 4
  • Does it have to be in pure javascript? How about jQuery? – DeFeNdog Commented Sep 10, 2014 at 21:01
  • I'm beginning to think that this is an XY problem. What is the actual issue that you are trying to solve? – Mr Lister Commented Sep 10, 2014 at 21:06
  • 1 Note not all browsers support dynamically changing the input type, I believe IE below 9 will not let you – Patrick Evans Commented Sep 10, 2014 at 21:06
  • 1 I would like to turn it into a clickable bookmark in Google Chrome. So jQuery wouldn't apply, just JavaScript. – A K Commented Sep 10, 2014 at 21:08
Add a ment  | 

4 Answers 4

Reset to default 4

To convert all elements of type password to text:

var arr = document.getElementsByTagName("input");
for (var i = 0; i < arr.length; i++) {
    if (arr[i].type == 'password') arr[i].setAttribute('type','text');
}

Note: Not all browsers allow dynamic changes to the type attribute on inputs.

This transforms every input of type password into input of type text for a document.

Array.prototype.slice.call(document.querySelectorAll('input[type="password"]'))
    .forEach(function (elt) {
        elt.setAttribute('type', 'text');
    });

You can get password field using the following query.

document.querySelector('input[type="password"]').type = "text";

If you're dealing with more than one field, you can use querySelectorAll And loop through them.

var pwds = document.querySelectorAll('input[type="password"]');
for (var i=0;i<pwds.length;i++){
pwds[i].type = "text";
}

The function is called document.getElementsByTagName (with an s) and it yields a list of elements. So you will need to address it with an index (a[0] for the first input, etc.)

I think the problem is determining which of the inputs you will need to change though, if they're not marked with IDs.

本文标签: javascriptHow to change the HTML input type attribute from 39password39 to39 text39Stack Overflow