Getting DOM element value using pure JavaScript

Adam Halasz picture Adam Halasz · Nov 13, 2010 · Viewed 477.1k times · Source

Is there any difference between these solutions?

Solution 1:

...and Solution 2:

function doSomething(id) {
  var value = document.getElementById(id).value;
  console.log(value);
  //...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />

Answer

yorick picture yorick · Nov 13, 2010

Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.

// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />

// JavaScript:
function(elem){
    var value = elem.value;
    var id    = elem.id;
    ...
}

This should also work.

Update: the question was edited. Both of the solutions are now equivalent.