JavaScript document.write

document.write() – This simply prints the specified text to the HTML page.

To print text literally, enter the text in single quote marks inside parentheses like so:

Syntax:

document.write(‘Learn web development!’);

Example:

<html>
<body>
<h1>
<script type=”text/javascript”>
document.write(‘Learn web development!’);
</script>
</h1>
</body>
</html>

The code above will print Learn web development! on html page.

The above code can also be used to write the text by assigning a variable as below.

var mytext = “Learn web development”;
document.write(mytext);

In JavaScript use ‘var’ in front of variable for declaring variable.

You can also combine variable values and text strings by using the + sign: the + sign act as concatenate operator.

var text1 = “Learn”;
var text2 = “web development things”;
document.write(‘<p>’ + text1 + ‘<br>’ + text2 + ‘</p>’);

The output of the above code will be:

Learn web development things

Posted in Javascript Tagged with: