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 < and >, 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>