WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to get the text inside an element using jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the jQuery text() method

You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

Let's take a look at an example to understand how this method basically works:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Get Text Content of an Element</title>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script>
  • $(document).ready(function(){
  •     // Show text content of plain paragraph
  •     $(".show-plain-text").click(function(){
  •         alert($(".plain").text());
  •     });
  •     
  •     // Show text content of formatted paragraph
  •     $(".show-formatted-text").click(function(){
  •         alert($(".formatted").text());
  •     });
  • });
  • </script>
  • </head> 
  • <body>
  •     <p class="plain">The quick brown fox jumps over the lazy dog.</p>
  •     <p class="formatted">The <strong>quick</strong> brown fox <em><sup>jumps</sup></em> over the <a href="#">lazy dog</a>.</p>
  •     <button type="button" class="show-plain-text">Get Plain Text</button>
  •     <button type="button" class="show-formatted-text">Get Formatted Text</button>
  • </body>
  • </html>

In the example above, when you try to get the text content of both the pain and formatted paragraphs it will produce the same result, since the text() method gets the combined text contents of all the selected elements, including their descendants.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements

Your Feedback:

We would love to hear from you, please drop us a line.