How To Replace Html Text With Jquery

jQuery is a popular JavaScript library that simplifies HTML document manipulation, event handling and animation. One of the most common tasks web developers perform is replacing text in HTML elements. In this blog post, we will learn how to replace HTML text using jQuery.

Prerequisites

To follow along with this tutorial, you should have a basic knowledge of HTML, CSS, and JavaScript. You should also have jQuery installed on your project. If you don’t have jQuery installed, you can include it via CDN by adding the following script tag to the head of your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Methods to replace text in jQuery

There are two main methods we can use to replace text in jQuery:

  • .text() – Sets or returns the text content of the selected elements.
  • .html() – Sets or returns the content (including HTML markup) of the selected elements.

Using the .text() method

The .text() method is used to set or return the text content of the selected HTML elements. When this method is used to return content, it returns the text content of all matched elements. When used to set content, it sets the text content of all matched elements.

Here’s an example of how to use the .text() method to replace the text content of an HTML element with the id “example”:

    $(document).ready(function() {
        $("#example").text("New Text");
    });
    

In the code above, we first wait for the document to be ready (using $(document).ready()). Then, we select the HTML element with the id “example” and use the .text() method to replace its text content with “New Text”.

Using the .html() method

The .html() method is similar to the .text() method, but it can also handle HTML markup. This means that you can use the .html() method to replace the content of an HTML element, including any HTML tags inside it.

Here’s an example of how to use the .html() method to replace the content of an HTML element with the id “example”:

    $(document).ready(function() {
        $("#example").html("&lt;strong&gt;New Text&lt;/strong&gt;");
    });
    

In the code above, we first wait for the document to be ready (using $(document).ready()). Then, we select the HTML element with the id “example” and use the .html() method to replace its content with “<strong>New Text</strong>” (which will render as bold text).

Conclusion

In this blog post, we learned how to replace HTML text using jQuery’s .text() and .html() methods. These methods are simple and powerful, and can be used to easily manipulate the text content of HTML elements in your web projects.