Captain Caveman
Captain Caveman

Reputation: 1536

Type of HTML element returned from document.getElementById String not Number

I am obtaining the value of an HTML element by using document.getElementById.innerHTML, and then passing that value to a function that returns the type of the value. I am then using an if / else if block to print out the type of value to the console. My problem, is that the typeof method always returns a type of string. If I don't use document.getElementById and declare the variable directly, typeof returns the correct type. Thanks for your help!

JS Fiddle here: http://jsfiddle.net/sY7uW/

// get innerhtml of div
var LowTemperature = document.getElementById('LowTemperature').innerHTML;

// check type from function return
if(check_type(LowTemperature) === 'number') {
    console.log(LowTemperature + " is a number");
}
else if(check_type(LowTemperature) === 'string') {
    console.log(LowTemperature + " is a string");
}

// return var type
function check_type(value) {
    return typeof value;    
}

Upvotes: 2

Views: 2124

Answers (4)

Display_name
Display_name

Reputation: 103

var LowTemperature = document.getElementById('LowTemperature').value;

or

var LowTemperature = parseInt(document.getElementById('LowTemperature').innerHTML);

Upvotes: 0

Adam Hopkinson
Adam Hopkinson

Reputation: 28793

You can try to parse the value as an integer, and then compare this back to the original:

if(parseInt(LowTemperature) == LowTemperature) alert("LowTemperature is an integer");

Upvotes: 1

user1710796
user1710796

Reputation:

What's happening here is that you're checking the type of number, which exists in string form. Try this instead:

// return var type
function check_type(value) {
    //you could also use parseInt or parseFloat here, but that would return a number for a string like "2014 asdf".  
    //By multiplying by 1, the value will be changed into a number if it is one
    var valueNumber = value*1;
    return typeof valueNumber;    
}

Upvotes: 0

ElGavilan
ElGavilan

Reputation: 6924

innerHTML will only return a string. You will need to parse that to an integer.

How do I convert a string into an integer in JavaScript?

Upvotes: 2

Related Questions