Getting DOM element value using pure JavaScript

前端 未结 5 2025
迷失自我
迷失自我 2020-11-28 06:36

Is there any difference between these solutions?

Solution 1:

相关标签:
5条回答
  • 2020-11-28 06:50

    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

    0 讨论(0)
  • 2020-11-28 06:52

    The second function should have:

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

    Then they are basically the same function.

    0 讨论(0)
  • 2020-11-28 07:03

    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.

    0 讨论(0)
  • 2020-11-28 07:06

    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;  
    }
    
    0 讨论(0)
  • 2020-11-28 07:09

    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.

    0 讨论(0)
提交回复
热议问题