Plumpie Plumpie - 1 year ago 88
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="">
<meta charset="utf-8" />

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



function printType() {
console.log(document.getElementById(inputField).value); //first try to get the value the regular way
); //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



Answer Source

You're missing quotes:


Should be:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download