jQuery text() method example

In this post,  we are going to see jQuery text method example.
text method is used to get text of all matched elements and text('new text') is used to set text for all matched elements. 
Syntax for text() :
$("selectors").text() 
Example :
$("div").text();
Syntax for text('new text') :
$("selectors").text('new text')
Example:
 $("div").text('this text is being set by text method');

Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery text method example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery text method example</h2>
<style>
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#textButton").click(function(){
         alert($("div").text()) ;
      });
$("#setTextButton").click(function(){
         $("div").text('this text is being set by text() method');
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="textButton">Using text</button>
  <button id="setTextButton">Using text('new text') </button>
<button id="reset">Reset</button>
<br />
<div class='blackBorder'>
 Hello world from java2blog!!!!
   </div>
<br/>
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: Jquery text method example on jsbin.com

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012