Main Tutorials

jQuery text() example

jQuery text() is used to get the contents of all the matched elements; While text(‘new text’) is used to replace or set the text contents of all the matched elements.

For example,


<div class="TClass">TEXT 1</div>
<div class="Tlass">TEXT 2</div>

1. $(‘.TClass’).text()

This will combine all the contents of the matched elements, get “TEXT 1 TEXT 2” as return. Unlike html(), get the content of the first element only.

2. $(‘.TClass’).text(‘This is new text‘)

All html tag < and > will be replace with &lt; and &gt;, no html effect will be apply.


<div class="AClass"><b>This is new text</b></div>
<div class="AClass"><b>This is new text</b></div>

jQuery text() example


<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	.textClass{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
	}
</style>

</head>
<body>
  <h1>jQuery text() example</h1>

  <div class="textClass">Text ABC ....</div>
  
  <div class="textClass">Text ABC 2....</div>
  
  <p>
  <button id="getText">text()</button>
  <button id="setText">text('xxx')</button>
  <button id="reset">reset</button>
  </p>
<script type="text/javascript">
	
    $("#getText").click(function () {
		
	  alert($('.textClass').text());
	  
    });
	
    $("#setText").click(function () {
		
	  $('.textClass').text('<b>This is a new text</b>');
	  
    });
	
    $("#reset").click(function () {
	  location.reload();
    });
	
</script>
</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mark
11 years ago

Thanks for these tutorials they have helped me a lot. I’m using clone and appendTo to print out a form I’ve developed in JQM. It works fine on the desktop but Android/iOS tablets aren’t working. I want to rollup the form and either print it to a file and mail it from the tablet or print it directly from the table without using a 3rd party printer app. Is there any way to do this? I have the form rollup working w/ clone & appendTo but can’t figure out how to save it as a text/html/pdf file to the table itself, or how to print directly from the tablet by clicking a button. Is there a way to do this in Jquery?