0

I was just curious I have 2 try and catch codes below both are supposed to to the exact same thing in 1 code the variable is message = document.getElementById("p01").innerHTML and in the other the variable is message = document.getElementById("p01") Why does 1 code work and the other not. they both looked the same to me

<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
    var message, x;
    // Why is this code not working I have added .innerHTML 
    message = document.getElementById("p01").innerHTML;
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 5)    throw "too low";
        if(x > 10)   throw "too high";
    }
    catch(err) {
        message = "Input is " + err; // the catch statement
    }
}
</script>

</body>
</html>

The below code does works

<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
    var message, x;
     //note message does not have a .innerHTML code here and this works?
    message = document.getElementById("p01");
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 5)    throw "too low";
        if(x > 10)   throw "too high";
    }
    catch(err) {
        message.innerHTML = "Input is " + err; // the catch statement

    }
}
</script>

</body>
</html>
Samir Tendulkar
  • 1,151
  • 3
  • 19
  • 47
  • 1st example points to the value and second points to the reference or object, thats why second example works. – Krishna Satwaji Khandagale Aug 26 '18 at 02:44
  • @Krishna I am sorry I dint understand could you dumb it down a bit – Samir Tendulkar Aug 26 '18 at 03:03
  • .innerHTML sets or returns inner html of given html tag. When you use .innerHTML at the right hand it returns html value means actual value , its not javascript object or anything like that its as good as a variable containing integer or string which now just can be modified but innerHTML object isnt referred and hence mot modified. – Krishna Satwaji Khandagale Aug 26 '18 at 03:06

0 Answers0