Skip to content
Related Articles

Related Articles

Difference between text() and html() method in jQuery

View Discussion
Improve Article
Save Article
  • Last Updated : 06 Jun, 2022

Text() Method: This method returns the text content of the selected elements. It overwrites the content of all the matches element while setting the content.

Syntax:

  • To return text content:
$(selector).text()
  • To set text content:
$(selector).text(content)
  • To set the text content using a function:
$(selector).text(function(index, currentcontent))

html() Method: This method is used to set or return the content (innerHTML) of the selected elements. It returns the content of the first matches element or sets the content of all matches elements.

Syntax:

Return content:

$(selector).html()

Set content:

$(selector).html(content)

Set content using a function:

$(selector).html(function(index, currentcontent))

Example: 

html




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
 
    <script>
        $(document).ready(function () {
            $("#button1").click(function () {
                alert("Using text()- " + $("#demo").text());
            });
            $("#button2").click(function () {
                prompt("Using html()- " + $("#demo").html());
            });
        });
    </script>
</head>
 
<body>
    <p id="demo">By clicking on the below buttons,
        <b>difference</b> between
        <i>text</i> and <i>html</i> in
        <b>jQuery</b> is shown.
    </p>
 
    <button id="button1">Text</button>
    <button id="button2">HTML</button>
</body>
 
</html>

Output:

Before clicking on buttons:

After clicking on Text Button:

After clicking on html Button:

Differences between text() and html() methods:

text() methodhtml() method
It is used to set or return the text content of selected elements.It is used to set or return the content of selected elements.
This method cannot be used on form inputs or scripts.This method can not be used for the value of a script element.
It is used in both XML and HTML documents.It is used only for HTML documents.
It is slower than html().It is ~2x faster than .text().
text() method overwrites the content of ALL matched elements.It returns the content of the FIRST matched element.
When text() method is used HTML markup will be removedIt overwrites the content of ALL matched elements.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!