JavaScript Basics: Displaying Text With JavaScript

If you’re getting into web development, one of the most frequent things you’ll do is use it to display/hide elements and text. In JavaScript, text is displayed in elements. This tutorial focuses on the use of the paragraph or ‘<p>element.

There are multiple ways to display text on a web page in JavaScript, the easiest is:

document.write("Text to display.");

Unfortunately, the document.write method will overwrite all the text on your page. As W3Schools said, it is only for testing. A much more useful method is document.getElementById. document.getElementById enables you to update or change the text in an element easily without affecting the rest of your page, as shown below.

<!DOCTYPE html>
<html lang="en-GB">

<script type="text/javascript">

  document.getElementById("myelement1") = "Hello world!";


<p id="myelement1"></p>


The JS code above creates an element with the id ‘myelement1’. You can give it your own name, if you wish. In case you were wondering, the lack of text between the two paragraph tags does mean that it’s blank. You won’t see it until you set it to display something using the JavaScript code above. It doesn’t even need to refresh the page, which is very beneficial from a performance standpoint. It’s instantaneous!

JavaScript has long been used to display little messages in pop ups, make calculations, and other things, but it has now become one of the most (if not the most) widely used scripting languages of the web, and is being utilized for the creation of single-page applications, which are gaining ground for their silky-smooth responsive interfaces.

Facebook Comments