Use document.write JavaScript to display text in HTML web page. This way is writing text in the document itself.
document.write("text to write")
There are a few methods to JS show text
- Writing text in the document itself
- innerHTML property
- document.write() method
- Displaying text in a message/alert box or use other prompt
- alert() box
- confirm()
- prompt()
Examples of JavaScript display text
Let’s have a look at some examples of specific methods.
innerHTML property
Using div with the ID, the script will auto load and write messages. You can use buttons and functions to avoid auto-load script.
<!DOCTYPE html>
<html>
<body>
<div id="show">
</div>
<script>
document.getElementById("show").innerHTML = "Read here written into the HTML and JavaScript code.";
</script>
</body>
</html>
Output:
document.write() method
Here is we are not using div or id, script will write the message on HTML Webpage.
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Display text")
</script>
</body>
</html>
alert() box
There are many ways to use alert box, the simple way is:-
<!DOCTYPE html>
<html>
<body>
<script>
alert(" alert Box")
</script>
</body>
</html>
Output:
Read more:– JavaScript alert box Examples
Q: How to display text from the input field as HTML code?
Answer: Using ajax you can do it, it dynamically display and update text in webpage elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="htmlinput"></textarea>
<div id="target"></div>
<script type="text/javascript">
$("#htmlinput").on("input",function(){
$("#target").html($(this).val());
});
</script>
</body>
</html>
Do comment if you have another question or doubts or suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version