Difference Between jQuery Text And jQuery HTML

What is the difference between $(selector).text() and  $(selector).html()?
 
Lets see.

The code given below is the sample HTML document and the respected design is next to it. 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("#btn").click(function(){  
  8.        $('#myElement1').text('First Div Changed...!');  
  9.        $('#myElement2').html("<p id='NewPara'>Second Div Changed...!</p>");  
  10.     });  
  11. });  
  12. </script>  
  13. </head>  
  14. <body>  
  15.   
  16. <div id="myElement1">Hello Div</div>  
  17. <Button id="btn">Click Me!</Button>  
  18. <div id="myElement2">  
  19.     <a href="http://wwww.google.com">Test Link</a>  
  20. </div>  
  21.   
  22. </body>  
  23. </html> 

The snapshot of HTML design.(w.r.t Developer mode.) is given above.



If you click on 'Click Me' button, you can see the command given below.

The first div (myElement1) text 'Hello Div' changed to 'First Div Changed...!'

The second div(myElement2) content that means link (Test Link) to  paragraph 'Second Div Changed...!', which you can see in the snapshot given below (w.r.t Developer mode.)

Conclusion
  • Use $(selector).text()- If you want to change(set) the text of HTML element.
  • Use $(selector).html()- If you want to replace the original element to new HTML element.
Ebook Download
View all
Learn
View all