Reputation: 1412
Is there any way to check if some HTML attribute are Boolean? for example:
<input type="text" name="input" disabled=""/>
Here the disabled
attribute is Boolean, I have some code and I need check before setting value whether that attribute is Boolean or not.
Why I need this?
As mentioned here we can have either ""
or property name itself as the valid value not true
or false
.
Upvotes: 3
Views: 2955
Reputation: 522081
There's basically no distinction on the level of HTML. If the attribute is simply the name without value, e.g. <input disabled>
, that's a sure sign that it's a boolean attribute. However, if it's using the name="value"
notation, then there's no way to distinguish it. Is class="class"
a boolean attribute? No, it's a classList
with one entry "class"
. How about foo=""
? Well, it's either a boolean attribute opting for the empty-value notation, or it's an attribute with no value set.
Only the interpreter assigns boolean-ness to an attribute; i.e. while parsing the HTML into a DOM, the interpreter sets DOM attributes like this, roughly speaking:
domElement.disabled = htmlElement.hasAttribute('disabled');
If you want to know what HTML elements are booleans, you need to do the same thing an interpreter does: keep a list of DOM elements whose attributes have types and interpret the HTML according to that specification.
Upvotes: 3
Reputation: 1263
To solve this issue, you have the typeof
operand in the following way:
var check_input = document.getElementById("check-input");
if(typeof(check_input.disabled) === "boolean"){
alert('Yes');
}
Here is a JSfiddle with the complete code. I hope that my answer can help you!
Upvotes: 0