Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
user784637 Avatar asked Aug 05 '11 14:08

user784637


People also ask

How do I print the results of a JavaScript function in HTML?

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.

Can we return value from JavaScript function?

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.


2 Answers

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());
like image 132
Matías Fidemraizer Avatar answered Sep 27 '22 17:09

Matías Fidemraizer


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();
like image 42
Maxx Avatar answered Sep 27 '22 18:09

Maxx