I have this HTML:
<input id="foo">Hello world!</input>
I wonder what the difference between
document.getElementById('foo').value
and
foo.value
is in the Javascript
I have this HTML:
<input id="foo">Hello world!</input>
I wonder what the difference between
document.getElementById('foo').value
and
foo.value
is in the Javascript
foo.value
takes advantage of the global variable foo
that is created when an element has an id
established for it. Both versions access the same object and work with the same data.
Accessing an element with just the id
has been around since the beginnings of JavaScript and remains today, but over time the Document Object Model API was created to have a more robust and complete way of interacting with documents.
Having said this, document.getElementById()
is the more modern approach. It's part of the Document Object Model API standard and is generally recommended as it is clearer and provides many ways to interact with elements in a web document.
Here's an example.
console.log(div.innerHTML);
div.innerHTML = "New Content!";
console.log(document.getElementById("div").innerHTML);
<div id="div">This is an element</div>