In this tutorial, we’ll look at how to display text in JavaScript, with two different purposes: replace it with another and add to an existing one.

Let’s create a simple HTML structure suitable for both. When the button is clicked, the text in the paragraph should be replaced by another. Onclick event is called text_out(). Next, we have to program this function in JavaScript.

<div id="text_out">
<p id="text_change">Change the text</p>
<hr>
<button onclick="text_out()" class="btn btn-danger">Change the text</button>
</div>

Replace text in JavaScript

We write the name of the function that matches the onclick event on the button, inside the curly brackets we will write the function code.

function text_out(){ }

To get a paragraph to work with declare a variable:

var p;

Assign the following object to the variable p. We obtained and put into the variable p, the entire paragraph with the identifier text_change.

p = document.getElementById('text_change');

In order to output anything (numbers, lines) inside any paired tag, we need to use the innerHTML construct. We’ll get a whole paragraph and instead of ‘Replace text’, output a new entry inside p:

p.innerHTML = 'Replace text';

After clicking the button, the replacement is successful.

Do we wonder what happens to the source code after the manipulation of the replacement? Let’s take a look at the code inspector for the developer and see that in the HTML code, too, there have been changes.

What happens if the quotes are left blank?

p.innerHTML = '';

Then the paragraph will be cleared, the current entry will be deleted, and no new entry will be inserted.

Add text to JavaScript

How do I add new text to an existing text without deleting the current one?

p.innerHTML += ' <i>on the website</i>';

We see a new assignment operator += that combines two strings. This expression can also be written in a similar way.

The two entries are equivalent.

 p.innerHTML = p.innerHTML + 'on the website';

We take what we have, add something new, and write it down again.

You may have noticed that the new text is enclosed in quotation marks along with the <i> tags, and the browser not only added it, but also processed it (added italics). In the innerHTML construct, the tags are handled by the browser.

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like