[SOLVED] Getting DOM element value using pure JavaScript

Table of Contents


Is there any difference between these solutions?

Solution 1:

function doSomething(id, value) {
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />

…and Solution 2:

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


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

Original answer

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:
    var value = elem.value;
    var id    = elem.id;

This should also work.

Answered By – yorick

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.