Plumpie Plumpie - 4 months ago 9
HTML Question

Js: GetElementByID() doesn't return my element

This has been asked 100x before but after reading a lot of those posts I'm still not sure what I'm doing wrong. The script is only executed when you press the button (so the textbox should exist in the DOM by the time the code is executed), Visual Studio even lets me autocomplete the getElementByID argument to inputField. Yet somehow it doesn't get the element and 'null' is printed on my screen.

My code is:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>

<!-- input field + button, and an empty value field -->
<input type="text" id="inputField" value="" />
<input type="button" onclick="printType()" />

</body>


<script>

function printType() {
console.log(document.getElementById(inputField).value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById(inputField)
)
); //also try get_type to see if it exists, we're expecting a string
}



//stole this function from a stackoverflow post
function get_type(thing) {
if (thing === null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}



</script>

</html>

Answer

You're missing quotes:

document.getElementById(inputField);

Should be:

document.getElementById('inputField');
Comments