How to Change Text in jQuery

Anika Tabassum Era Feb 15, 2024
  1. the text() Method in jQuery
  2. Use the text() Method to Change Text Directly Using jQuery
  3. Use the text() Method to Change Text With Click Events Using jQuery
How to Change Text in jQuery

In jQuery, multiple conventions exist to solve problems in fewer lines of code. Similarly, an addition is the text() method.

the text() Method in jQuery

Generally, the text() function returns the text value of a particular element when applied to its instance. Suppose we have a p tag with a message: It's a line.

So we have the syntax like this:

<p id="line"> It's a line.</p>

When we apply the text() method on the instance, it will return "It's a line.". The syntax is as follows:

$('#line').text();  // output = "It's a line."

In our example sets, we will demonstrate how we can alter the existing text with something new according to preference. So, the first instance will have a direct changing implementation; the next one will be conducted via a click event. Let’s hop in!

Use the text() Method to Change Text Directly Using jQuery

The text() method will take the new text value as a string parameter for this example. You can also initiate a dynamic value of your will.

It will simply change the value of the static HTML body and the preview page. Let’s check the code fences to examine this.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
    $('#title').text("New Text");
});
</script>
</head>
<body>
<p id='title'>Text</p>

Output:

Use text() Method to Change Text Directly - Output 1

Use text() Method to Change Text Directly - Output 2

Use the text() Method to Change Text With Click Events Using jQuery

The procedure here will be similar to the previous one. If we make the basic difference here, we will make a click event to trigger the change effect.

We will also see how the HTML body content gets biased when clicking on the click event. Let’s jump to the code lines.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
  $('#press').click(function(){
    $('#title').text("Text Altered");
});
  });
</script>
</head>
<body>
<p id='title'>Text</p>
<button id="press">Text Change</button>

Output:

Use text() Method to Change Text with Click Events - Output 1

Use text() Method to Change Text with Click Events - Output 2

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - jQuery Text