How to replace innerHTML of a div using jQuery?

Learn, how to trigger the same function from multiple events using jQuery?
Submitted by Pratishtha Saxena, on August 23, 2022

InnerHTML over here means the HTML content that is written in a particular element. It consists of text, spaces, CSS, everything. innerHTML is used to set and return the HTML content using JavaScript and jQuery. Mentioning innerHTML after the selected element will help to set or get the HTML content of that element.

Syntax:

value = $('selector').innerHTMl;

But the task over here is to replace the innerHTML using jQuery. As we discussed above, using innerHTML we can get or set the HTML content, also we can modify it or delete it. For this, we need to use is a simple jQuery method html().

With this, it is possible to access the innerHTML of any document. Using the same, few changes can be made, modifications can be done to the text and content of any element, also the element can be emptied with this if necessary.

Syntax:

$('selector').html('content');

Let's take an example of this.

Example to replace innerHTML of a div using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Replace InnerHTML of DIV</h2>
    <p>To change the sentence given below, click on the button.</p>
    <br><br>
    <h3 id="myH">Welcome To Include Help !!</h3>
    <br><br>
    <button type="button" id="button1">Click Here</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
     $('#button1').click(function(){
         $('#myH').html('Thank you for visiting us !!');
     });
    });
  </script>
</html>

Output:

Example 1: Replace innerHTML of a div

After clicking on "Click Here" button.

Example 2: Replace innerHTML of a div





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.