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.
- <!DOCTYPE html>
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
- <script>
- $(document).ready(function(){
- $("#btn").click(function(){
- $('#myElement1').text('First Div Changed...!');
- $('#myElement2').html("<p id='NewPara'>Second Div Changed...!</p>");
- });
- });
- </script>
- </head>
- <body>
-
- <div id="myElement1">Hello Div</div>
- <Button id="btn">Click Me!</Button>
- <div id="myElement2">
- <a href="http://wwww.google.com">Test Link</a>
- </div>
-
- </body>
- </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.