I couldn't find this specific wording anywhere and so the solution was hard to find.
I have an element and I want to find out if it is disabled or not in my javascript. How do I get the value of the disabled attribute of the element?
I couldn't find this specific wording anywhere and so the solution was hard to find.
I have an element and I want to find out if it is disabled or not in my javascript. How do I get the value of the disabled attribute of the element?
When I tried searching for this specific wording I found a lot of related questions on stackoverflow, but not this one. I figured it out from other posts and what I already know, but since I did not find this specific question clearly asked in stackoverflow, I hope this helps someone less experienced find the answer.
You should be looking for the value of the disabled
property of the HTML element instead of the attribute.
disabled
is both an attribute and a property, but only the property is really useful. You get it in your js like this:
let myElement = document.document.getElementsByTagName('input')[0];
let is_disabled = myElement.disabled;
// true or false
The MDN page on disabled
is no help. It only talks about disabled
as an attribute. Maybe there is another page in the MDN that I have not found yet that explains it better.
An attribute has to do with HTML. In the code below, class
is an attribute:
<input class="the-best"/>
It has a value right there in the HTML. You get the value of an attribute with .getAttribute()
:
let classNames = myElement.getAttribute('class');
// "the-best"
A property has to do with javascript. In javascript, when you get an element you get an object with a bunch of properties and methods. For example, you can get the inner height of the element like this:
let inner_height = myElement.clientHeight;
// Some number
In HTML, disabled
looks like this:
<input disabled/>
You can see disabled
in the HTML, but it does not have a value. If it does have any value, then it is disabled, even if that value is "false"
. You can do myElement.setAttribute('disabled', 'false')
and you'll get <input disabled="false">
which still disables the element. Basically, if disabled
is in the HTML in any way the element is disabled. If it is not in the HTML then the element is NOT disabled. .getAttribute()
will work like this:
// <input disabled/>
let is_disabled = myElement.getAttribute('disabled');
// "" - an empty string
// <input/>
let is_disabled = myElement.getAttribute('disabled');
// null
You can probably still use .getAttribute()
if you want since you can check for a string
or null
, but people sometimes do weird things with their HTML and the "values" of these kinds of attributes (like what I described above).