La forma oficial de establecer el disabledatributo en un HTMLInputElementes esta:
var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);
// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');
Si bien la respuesta de @ kaushar es suficiente para habilitar y deshabilitar un HTMLInputElement, y probablemente sea preferible para la compatibilidad entre navegadores debido a la falla histórica de IE setAttribute, solo funciona porque las Elementpropiedades sombrean los Elementatributos. Si se establece una propiedad, el DOM usa el valor de la propiedad por defecto en lugar del valor del atributo equivalente.
Hay una diferencia muy importante entre propiedades y atributos. Un ejemplo de una HTMLInputElement propiedad verdadera es input.value, y a continuación se muestra cómo funciona el sombreado:
var input = document.querySelector('#test');
// the attribute works as expected
console.log('old attribute:', input.getAttribute('value'));
// the property is equal to the attribute when the property is not explicitly set
console.log('old property:', input.value);
// change the input's value property
input.value = "My New Value";
// the attribute remains there because it still exists in the DOM markup
console.log('new attribute:', input.getAttribute('value'));
// but the property is equal to the set value due to the shadowing effect
console.log('new property:', input.value);
<input id="test" type="text" value="Hello World" />
Eso es lo que significa decir que las propiedades sombrean los atributos. Este concepto también se aplica a las propiedades heredadas en la prototypecadena:
function Parent() {
this.property = 'ParentInstance';
}
Parent.prototype.property = 'ParentPrototype';
// ES5 inheritance
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
function Child() {
// ES5 super()
Parent.call(this);
this.property = 'ChildInstance';
}
Child.prototype.property = 'ChildPrototype';
logChain('new Parent()');
log('-------------------------------');
logChain('Object.create(Parent.prototype)');
log('-----------');
logChain('new Child()');
log('------------------------------');
logChain('Object.create(Child.prototype)');
// below is for demonstration purposes
// don't ever actually use document.write(), eval(), or access __proto__
function log(value) {
document.write(`<pre>${value}</pre>`);
}
function logChain(code) {
log(code);
var object = eval(code);
do {
log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);
object = object.__proto__;
} while (object !== null);
}
Espero que esto aclare cualquier confusión sobre la diferencia entre propiedades y atributos.