0

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

froggyman
  • 105
  • 2

1 Answers1

1

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • " global variable foo that is created when an element has an id established for it" Is this reliable? What's the point of `document.getElementById()` if it is? – gforce301 Apr 18 '17 at 15:46
  • @gforce301 It is reliable. `document.getElementById()` is one of many methods and properties that allow access to and interaction with a web document. As such, the DOM API (explained in my answer above) is recommended over just using the `id`. – Scott Marcus Apr 18 '17 at 15:48