How to replace innerHTML of a div using jQuery?

To replace innerHTML of a div in jQuery, use the html() or text() method. The html() method sets or returns the HTML content of an element, while text() sets or returns the text content without HTML formatting.

Using the html() Method

The html() method is the jQuery equivalent of JavaScript's innerHTML property. It can both get and set the HTML content of selected elements ?

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
   $(document).ready(function(){
      $("#button1").click(function(){
         $('#demo').html('Demo text with <b>bold</b> formatting');
      });
   });
   </script>
</head>
<body>

<div id="demo">This is <b>Amit</b>!</div>
<button id="button1">Replace with html()</button>

</body>
</html>

Using the text() Method

The text() method replaces content with plain text only, ignoring any HTML tags ?

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
   $(document).ready(function(){
      $("#button2").click(function(){
         $('#demo2').text('Plain text content - HTML tags are ignored');
      });
   });
   </script>
</head>
<body>

<div id="demo2">This is <b>original content</b>!</div>
<button id="button2">Replace with text()</button>

</body>
</html>

Conclusion

Use html() when you need to insert HTML content with formatting, and text() when you want to insert plain text content safely without HTML interpretation.

Updated on: 2026-03-13T18:55:58+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements