replace input with javascript
Hello everybody I'm trying to replace the 'text' input type to 'password' . And it works with following code :
function replaceT(obj){
var newO=document.createElement('input');
newO开发者_JAVA技巧.setAttribute('type','password');
newO.setAttribute('name',obj.getAttribute('name'));
obj.parentNode.replaceChild(newO,obj);
newO.focus();
}
But I want to add class of my previous input to the new input and I tried something like this :
function replaceT(obj){
var newO=document.createElement('input');
newO.setAttribute('type','password');
newO.setAttribute('className' obj.getAttribute('class'));
newO.setAttribute('name',obj.getAttribute('name'));
obj.parentNode.replaceChild(newO,obj);
newO.focus();
}
What am I doing wrong, or if that is not possible, how to set the new class manually .. Thank you
This should work across all browsers:
newO.className = obj.className;
I'm not sure whether you should use className
or class
in setAttribute
, but whatever it is, it is definitely the same as in getAttribute
, so this is definitely wrong:
newO.setAttribute('className' obj.getAttribute('class'));
newO.setAttribute('className' obj.getAttribute('class'));
You are using 'className' for setting the attribute, but 'class' for getting it. Both must be 'className'.
Sorry for going in the other direction, but why do you replace the element instead of just changing its type in the first place? Than you won't need to worry about adding the same className to the new element.
Just being curious.
精彩评论