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?
JavaScript Print JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.
JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running. JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return.
There are some options to do that.
One would be:
document.write(produceMessage())
Other would be appending some element in your document this way:
var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);
Or just:
document.body.appendChild(document.createTextNode(produceMessage()));
If you're using jQuery, you can do this:
$(document.body).append(produceMessage());
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With