Search code examples
javascriptgetelementbyid

getElementById returns an object instead of an element


I have an input with an id of name:

<input type="text" id="name">

When I run document.getElementById("name") in the console, I get the element itself (<input type="text" id="name">), but as soon as I assign it to a variable (var name = document.getElementById("name");), I get the string "[object HTMLInputElement]".

Why does that happen? Why can't I just get the selected input element, instead of the input element object?

Thanks.


Solution

  • if you use without

    var name = document.getElementById("name")
    

    or any other variable than name,

    var myvar = document.getElementById("name")
    

    you'll get

    <input type="text" id="name">
    

    name is property of some DOM elements.

    have a look up here