Home > Mobile >  <input> has no value in HTML but does in JavaScript? [duplicate]
<input> has no value in HTML but does in JavaScript? [duplicate]

Time:09-18

I have found an <input type="text" ... element on a page, for which $('thatElement').val() and $('thatElement')[0].value return the value, the value is displayed in the rendered output, but there is no value="..." attribute on the element itself.

How can there be no value attribute in the HTML for an input element, but it still has a value and still displays its value?

Browser console:


> $('thatElement')[0].value
'The text that the page shows inside of the input'
> $('thatElement')[0].outerHTML
'<input autocomplete="off" type="text" readonly spellcheck="false">'

CodePudding user response:

There's a difference between the source of a document and its DOM representation. The source file is static and won't change. The DOM might change. I think it depends on how you manipulate it.

In this example the input value is set but the DOM isn't updated: (run and inspect the result)

document.querySelector('input').value = 42;
<input />

In this example both the input and the DOM is updated:

document.querySelector('input').setAttribute('value', 'foobar');
<input />

  • Related