Getting DOM element value using pure JavaScript

2019-01-06 13:09发布

Is there any difference between these solutions?

Solution 1:

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

// JavaScript:
function doSomething (id, value) {
    // ...
}

...and Solution 2:

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

// JavaScript:
function doSomething(id){
    var value = document.getElementById(id).value;
    // ...
}

4条回答
Emotional °昔
2楼-- · 2019-01-06 13:42

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;  
}
查看更多
We Are One
3楼-- · 2019-01-06 13:50

The second function should have:

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

Then they are basically the same function.

查看更多
看我几分像从前
4楼-- · 2019-01-06 13:51

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.

查看更多
狗以群分
5楼-- · 2019-01-06 13:58

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.

查看更多
登录 后发表回答