Skip to content
Related Articles

Related Articles

Improve Article
jQuery | text() Method
  • Last Updated : 27 Feb, 2019

This method is used to set or return the text content of the element. While setting the content, it overwrites the content of all the matched elements. The returned content of text method() is used to return the text content of all matched elements.

Syntax:

  • Return text syntax:
    $(selector).text()
  • Set text syntax:
    $(selector).text(content)
  • Set text using a function:
    $(selector).text(function(index, currentcontent))

Property Values:

  1. Content Required: It is used to set the new text content for the element.
  2. Function(index, currentcontent): It is used to specify a function that will return the new text content for the selected elements.
    • index: It returns the index position of the element.
    • currentcontent: It returns the current content of element.

Example-1: Set text syntax.




<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
    Geeks <button onclick="function()">Click me
        </button>
      </center>
  </h1>
  
    <script src=
  </script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("p").text("Jquery_text_method");
            });
        });
    </script>
  
    <p>GeeksforGeeks</p>
    <p>Jquery</p>
  
</body>
  
</html>

Output:



Before clicking on the button:

After clicking on the button:

Example-2: Return text syntax.




<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
     Geeks <button onclick="function()">Click me
        </button>
      </center
  </h1>
  
    <script src=
  </script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                alert($("p").text());
            });
        });
    </script>
  
    <p>GeeksforGeeks</p>
    <p>Jquery</p>
  
</body>
  
</html>

Output:

Before clicking on the button:

After clicking on the button:

Example-3: Set text using a function.




<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
      Geeks <button onclick="function()">Click me
        </button>
      </center>
  </h1>
    <script 
  </script>
    
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("p").text(function(n) {
                return "Index No. of Element: " + n;
                });
            });
        });
    </script>
    
    <p>GeeksforGeeks</p>
    <p>Jquery_textmethod()</p>
  
</body>
  
</html>

Output:

Before clicking on the button:

After clicking on the button:




My Personal Notes arrow_drop_up
Recommended Articles
Page :