Search code examples
javascripthtmlgetelementsbytagname

Element type 'date' when accessed by getElementsByTagName() shows it as 'text'


When I try to access the type of the first textbox, it shows "text" instead of "date" whereas when I try to access the size of the text, it shows the correct value.

Why is it so? How can I check whether the type of a particular textbox is date or text in Javascript?

<html>
<head>
<script>
function getElements()
  {
  var x=document.getElementsByTagName("input");
  alert(x[0].type);
  }
</script>
</head>
<body>

<input type="date" size="25"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<input type="text" size="20"><br><br>
<input type="button" onclick="getElements()" value="How many input elements?">

</body>
</html>

Solution

  • Date and time based input times are usually not available on desktop browsers. As such, input elements with such a type defined will default to the text type.

    So when you access the element’s type you get whatever type the browser is actually using for that element.

    If you want to get the value you actually specified, ignoring whether the browser knows it or not, you can use getAttribute to the the original value:

    alert(x[0].getAttribute('type')); // date