Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) {_x000D_
console.log(value);_x000D_
//..._x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
_x000D_
...and Solution 2:
function doSomething(id) {_x000D_
var value = document.getElementById(id).value;_x000D_
console.log(value);_x000D_
//..._x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething(this.id)" />
_x000D_
This question is related to
javascript
get
element
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {_x000D_
console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
if DOM element has id then you can use it in js directly
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;
}
The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.
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.
Source: Stackoverflow.com