views:

87

answers:

2

Hi,

I have just started learning Javascript. I want "Hello World!" to be written to a webpage once a user clicks a button. I have tried this:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
document.write("Hello World!");
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

I can get it to do a window.alert("Hello World!") but not do document.write("Hello World!") for some reason. What happens is the button disappears and no text is displayed. My guess is that the problem is in the document.write but I do not know how to work around it. Any suggestions?

+5  A: 

Because the document has already been written at that point. You can set text like so:

<button id="lol">blah</button>
<script>
    function setText( obj, to ) {
        obj.textContent? obj.textContent = to : obj.innerText = to;
    }
    var lol = document.getElementById('lol')

    lol.onclick = function() {
        var p = document.createElement('p');
        document.body.appendChild(p);
        setText( p, 'hi' );
    }
</script>

Another popular but often looked down technique would be innerHTML.

meder
How do I make a new document then?
thyrgle
you don't. you use alternate methods like creating new text nodes and elements or altering existing ones.
meder
Thnx. Will accept when I get the chance.
thyrgle
Why is innerHTML looked down upon? It's much simpler.
Mike Sherov
It's frowned upon because it wasn't initially a standard, though nowadays I would assume people are more lenient because the jQuery `html` method is just innerHTML and innerHTML has become part of the HTML 5 spec.
meder
+2  A: 

Document.write is used to write to the currently loading HTML file. Once the page has been loaded, and a user begins interacting with the page, document.write is useless.

Mike Sherov