How to Change HTML Text With jQuery

In this tutorial we're going to walk you through how to change HTML text on your website using jQuery code to make that text change.

In this tutorial we’re going to explore how to change the text within a HTML element. But first let’s explore why you’d want or need to do that.

In many cases you may have situations where the text within a div, h1, h2 or any other element doesn’t need to remain static within the web page. For example when hovering over a button, or after clicking a button the text may need to change. This level of functionality seems complicated and like it would involve a substantial amount of code but can be relatively simple with jQuery.

To implement this we simply need to use the .text(text) method to change the text within the on-page element.

So for example let’s say you want to change the text within a div such as:

The Code:
<div class=”thisisaclass”> 

<p> Lorem Ipsum </p>  

</div>

So in the above example we want to change the ‘Lorem Ipsum’ text.

We would use $(“div.thisisaclass”).text(“<p>Lorem Ipsum Dolor Sit Amet</p>”);

So let’s look at this in more detail:

The initial part of this the: $(“div.thisisaclass”) targets the div class that we set out above by identifying the div part and then the class name.

The next part is the .text(<p>Lorem Ipsum Dolor Sit Amet</p>”); section this in effect targets the text within the div class that we mentioned above and changes it to “Lorem Ipsum Dolor Sit Amet” and adds the <p> tags to it. We do this as the text currently within that div has <p> tags and this will update everything in the div class.

You can do this with most elements simply by swapping the div that we used in the example above for another element and that element’s specific class. Or if you wanted to change all text on a page you could just use the element for example $(“h3”).

Further reading:

Adding jQuery to WordPress

Adding Javascript to WordPress

We hope this helps you to understand how to change HTML text with jQuery on your site, we’d appreciate a share or any comments if you found this useful, thanks!

Tech Typed
Tech Typed
Articles: 186

Leave a Reply

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