-3

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">'
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • Depends on how you compare. Do you by any chance compare the page source code (NOT via dev tools in any browser) and the JS-evaluation? Because source code (by right-click -> show source code) will only show what comes from the server intially, which may very well have been changed since then. – ArSeN Sep 12 '21 at 09:06
  • Please provide a [mcve] – Quentin Sep 12 '21 at 09:06
  • @ArSeN inspect element, and even `.outerHTML` shows no value attribute – theonlygusti Sep 12 '21 at 09:09
  • 1
    [Attributes are not the same as properties](https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html). The attribute only shows the initial value and (usually) never changes. The property has the current value but does not show in the HTML. – TiiJ7 Sep 12 '21 at 09:18

1 Answers1

1

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 />
customcommander
  • 17,580
  • 5
  • 58
  • 84