Gopal1216
Gopal1216

Reputation: 437

Displaying data in a html element

I have a small doubt. I want to display some data on my page using innerHTML property. But when I try to do so, the data wont render on my page. But if I use document.writeln(), the data is rendering on the page. I want to display the data in the span element with id="verify". How can I do that? Here is my code:

<script>
    var now = new Date();
    var hours = now.getHours();
    var name, greeting;
    if(hours < 12)
    {
        greeting = "Good Morning";
    }
    else
    {
        //hours = hours - 12;
        if(hours < 18)
        {
            greeting = "Good Afternoon";
        }
        else
        {
            greeting = "Good Evening";
        }
    }
    if(document.cookie)
    {
        var newCookie = unescape(document.cookie);
        var cookieVals = newCookie.split("=");
        name = cookieVals[1];
    }
    else
    {
        name = window.prompt("Please enter your name","name");
        document.cookie = "name=" + escape(name);
        //document.writeln(greeting + " "+ name + ", welcome to JavaScript programming!" );
        //document.writeln( "<a href = 'javascript:wrongPerson()'> " +"Click here if you are not " + name + "</a>" );
        var a = greeting + " "+ name + ", welcome to JavaScript programming!</h1>" + "<a href = 'javascript:wrongPerson()'> " +"Click here if you are not " + name + "</a>";
        document.getElementById("verify").innerHTML = a;
    }
    function wrongPerson()
    {
        document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT";
        location.reload();
    }
    </script>
    <span id="verify"></span>

Upvotes: 0

Views: 196

Answers (1)

Oryan Moshe
Oryan Moshe

Reputation: 139

In addition to Cheery's answer, you should always put your javascript at the end of your body, unless you need it to display something on the page before it loads. This will give you better performances and will probably eliminate most of these small mistakes like trying to fetch an element before the page loads.

Upvotes: 1

Related Questions