Paul Smith
Paul Smith

Reputation: 43

numeric value from html being read as a string

I've simplified my code here to show that I have a value which is passed in to "mydiv1" which is always a number. I would like to be able to reference this to perform actions depending on whether it's negative or positive, but it must be being seen as a string. Is there any way this value can be got as a number? All topics i've seen such as parseInt() seem to relate to when a variable is specified rather than got from the html.

<html>
<head>
<script type="text/javascript">
    function myFunction() {
        var firstDivContent = document.getElementById('mydiv1');
      //  var firstDivContent =  "23";
        if (firstDivContent > 0) {
            alert('positive')
        }
        else if (firstDivContent < 0) {
            alert ('negative')
        }
    }
</script>
</head>
<body onload="myFunction();">
<div id="mydiv1">23</div>
</body>
</html>

Upvotes: 0

Views: 187

Answers (3)

&#193;lvaro Touz&#243;n
&#193;lvaro Touz&#243;n

Reputation: 1230

I prefer to use the "+" operator to make the cast to number more cleanly, in this demo, you can test it:

function myFunction() {
        var firstDivContent = document.getElementById('mydiv1');
      //  var firstDivContent =  "23";
        if (firstDivContent > 0) {
            alert('positive')
        }
        else if (firstDivContent < 0) {
            alert ('negative')
        }
    }

Upvotes: -1

Marco
Marco

Reputation: 7287

<html>
<head>
<script type="text/javascript">
    function myFunction() {
        var firstDivContent = document.getElementById('mydiv1');
        firstDivContent = parseFloat(firstDivContent.innerHTML);
        if (firstDivContent > 0) {
            alert('positive')
        }
        else if (firstDivContent < 0) {
            alert ('negative')
        }
    }
</script>
</head>
<body onload="myFunction();">
<div id="mydiv1">23</div>
</body>
</html>

Use innerHTML to get the HTML content of a div and then use parseFloat to convert the string to a number.

Upvotes: 2

Weedoze
Weedoze

Reputation: 13953

You should get the innerHTML of your element. Then you can use parseInt() or +yourVar to convert the string to a number

var firstDivContent = +(document.getElementById('mydiv1').innerHTML);
if (firstDivContent > 0) {
  alert('positive')
} else if (firstDivContent < 0) {
  alert('negative')
}
<div id="mydiv1">23</div>

Upvotes: 1

Related Questions