[javascript] How to get html to print return value of javascript function?

What is the preferred syntax to get html to print return value of javascript function?

function produceMessage(){
    var msg= 'Hello<br />';
    return msg;
}

EDIT: Yikes, too many answers without me clarifying what I meant. I know how to do it via the script tag. However, let's say I wanted to make the message red. Would I just encase the script tag inside my css like so?

<div style="color:red><script>document.write(produceMessage())</script></div>

I guess my main question was, should you be using document.write to get the return values to print?

This question is related to javascript html

The answer is


Or you can tell javascript where to write it.

<script type="text/javascript">
    var elem = document.getElementById('myDiv');
    var msg= 'Hello<br />';
    elem.innerHTML = msg;
</script>

You can combine this with other functions to have function write content after being evaluated.


It depends what you're going for. I believe the closest thing JS has to print is:

document.write( produceMessage() );

However, it may be more prudent to place the value inside a span or a div of your choosing like:

document.getElementById("mySpanId").innerHTML = produceMessage();

you could change the innerHtml on an element

function produceMessage(){
    var msg= 'Hello<br />';
     document.getElementById('someElement').innerHTML = msg;
}

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.


<script type="text/javascript">
    document.write("<p>" + Date() + "</p>");
</script>

Is a good example.


if you really wanted to do that you could then do

<script type="text/javascript">
    document.write(produceMessage())
</script>

Wherever in the document you want the message.