Search code examples
javascripthtmlgoogle-chromedomw3c

Why inputElement.maxLength returns -1?


I wonder why default maxLength/minLength property for HTMLInputElement is set to -1 by default.

There is also confusing behavior like below:

  1. Example
<input type="text" />
const inputElement = document.querySelector('input');
console.log(inputElement.maxLength) // -1

  1. I set maxLength programatically
inputElement.maxLength = 2;
console.log(inputElement.maxLength) // 2

and html will reflect as

<input type="text" maxlength="2" />

  1. I remove maxlength="2" manually from devtools.
<input type="text" />

I get

console.log(inputElement.maxLength) // undefined

can someone tell me why is that? There is no such a thing in documentation, but i can see that every browser is pretty consistent in this.

[Edit] 3. is wrong in this example, it is return -1 https://stackoverflow.com/a/75541575/10465908


Solution

  • So answer to my original question is https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#limited-to-only-non-negative-numbers as maxLength is type long.

    But I discovered some interesting things during the investigation:

    1. WebKit returns -1 but real maxlength is 524288, other engines seems not have this limitation.
    2. It was 524288 in other browsers way back
    3. During IDL attributes spec, they all decided to return -1