Reputation: 10081
I was wondering if there is a way to get the default value of an attribute that has not been set.
For example in this easy snippet:
let inputs = document.querySelectorAll('input');
inputs.forEach(function(elm){
console.log(elm.getAttribute('type'));
});
<input />
<input type='integer'/><!-- This one is invalid -->
<input type='number'/>
<input type='submit'/>
… The result is "null" for the first one, and "integer" for the second.
We all know that without the type
attribute explicitly defined (or an invalid one, like in my snippet), the input
is treated by default as a input type="text"
. But, is there any way to display that?
I mean… Is there any function that would return "text" instead of "null" or the faulty value?
Something that may be used like this: input.getAttributeOrDefault("type")
?
Thanks in advance for any answer.
Upvotes: 0
Views: 405
Reputation: 1976
Default type value if not provided for an input element is 'text'. You can acces it with this :
let input = document.querySelector('input');
console.log(input.type);
<input />
-- EDIT -- Beware integer is not a valid type so it will fallback to text
let inputs = document.querySelectorAll('input');
inputs.forEach(function(elm){
console.log(elm.type);
});
<input />
<input type='integer'/>
<input type='number'/>
<input type='submit'/>
Upvotes: 2
Reputation: 5162
To access the input type you can use the following code by using input.type
let input = document.querySelector('input');
console.log(input.type);
<input />
EDIT
The code using input.type
works in all the valid cases. type = "integer"
should be replaced with type = "number"
. If the type is not recognized as valid by the interpreter then its set to default text
let inputs = document.querySelectorAll('input');
inputs.forEach(function(elm){
console.log(elm.type);
//console.log(elm.getAttribute('type'));
});
<input />
<input type='number'/>
<input type='submit'/>
Upvotes: 1