Search code examples
javascriptgetelementbyid

How can getElementById(idname) find the right element and yet element.id shows the id as "" and not as "idname"?


I have searched and searched, but did not find a similar situation and answer.

I am able to access an element with getElementById(idname) and even have access to its value, however when I try to access its id it displays as "" instead of "idname". How is this possible?

Example:

console.log(document.getElementById("test").value); //is shown as Hello World
console.log(document.getElementById("test").id); //is shown as "" and not as "test"

Edit: I have found the answer see below.


Solution

  • I did some tests and found out why document.getElementById(idname) retrieves the element but not its id. Our testing browser is IE11 that runs in compatibility mode (the project was originally for IE8) and IE can fetch a name attribute with document.getElementById and thus the element is retrieved but has no id.

    A simple example:

    <input name = "test" value = "test value"></input>
    <input id = "test2"></input>
    

    Javascript:

    console.log("test id :" + document.getElementById("test").id);
    console.log("test2 id :" + document.getElementById("test2").id);
    console.log("test value :" + document.getElementById("test").value);
    

    Results:

    test id :
    test2 id :test2
    test value :test value