Getting DOM element value using pure JavaScript

JavascriptGetElement

Javascript Problem Overview


Is there any difference between these solutions?

Solution 1:

function doSomething(id, value) {
  console.log(value);
  //...
}

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

...and Solution 2:

function doSomething(id) {
  var value = document.getElementById(id).value;
  console.log(value);
  //...
}

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

Javascript Solutions


Solution 1 - Javascript

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:
function(elem){
    var value = elem.value;
    var id    = elem.id;
    ...
}

This should also work.

Solution 2 - Javascript

The second function should have:

var value = document.getElementById(id).value;

Then they are basically the same function.

Solution 3 - Javascript

In the second version, you're passing the String returned from this.id. Not the element itself.

So id.value won't give you what you want.

You would need to pass the element with this.

doSomething(this)

then:

function(el){
    var value = el.value;
    ...
}

Note: In some browsers, the second one would work if you did:

window[id].value 

because element IDs are a global property, but this is not safe.

It makes the most sense to just pass the element with this instead of fetching it again with its ID.

Solution 4 - Javascript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

Solution 5 - Javascript

There is no difference if we look on effect - value will be the same. However there is something more...

Solution 3:

function doSomething() {
  console.log( theId.value );
}

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

if DOM element has id then you can use it in js directly

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam HalaszView Question on Stackoverflow
Solution 1 - JavascriptyorickView Answer on Stackoverflow
Solution 2 - JavascriptEvan MulawskiView Answer on Stackoverflow
Solution 3 - Javascriptuser113716View Answer on Stackoverflow
Solution 4 - JavascriptR. Z.View Answer on Stackoverflow
Solution 5 - JavascriptKamil KiełczewskiView Answer on Stackoverflow