text method in jQuery with example
1. text() method gets the combined text contents of each element in the set of matched elements, including their descendants.
2. text() method can be used in both xml and html documents.
3. text() method cannot be used for input elements. For input elements val() method can be used to access their text.
4. text() method returns text, CDATA nodes and as well as element nodes.
Example 1 :
<html>
<head>
<title>text</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#textP").click(function () {
var textP = $("#targetP").text();
alert(textP);
});
$("#textUL").click(function () {
var textUL = $("#targetUL").text();
alert(textUL);
});
});
</script>
</head>
<body>
<p id="targetP">This is 99codingexamples. <span>This is span element.</span></p>
<b>List of Players :</b>
<ul id="targetUL">
<li>Cesc Fabregas</li>
<li>Thierry Henry</li>
<li>Ronaldinho</li>
<li>Tomas Rocisky</li>
<li>Robin Van Persie</li>
</ul>
<input type="button" id="textP" value="text() for P" />
<input type="button" id="textUL" value="text() for UL" />
</body>
</html>
Demo :In above example, we have rendered a paragraph element and unordered list. We have two buttons for each element respectively. On click of button we are fetching text of respective element using text() method and displaying it using alert. The above example shows that text() method returns text of all descendants.
Example 2 :
<html>
<head>
<title>text</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#myButton").click(function () {
$("#targetP").text("20 Fingers and 2 Brains. You clicked text() button.");
});
});
</script>
</head>
<body>
<p id="targetP">This is 20 Fingers and 2 Brains.</p>
<input type="button" id="myButton" value="text()"/>
<input type="button" id="reset" Value="Reset" onclick="location.reload()" />
</body>
</html>
Demo :In the above example, we have a paragraph element. On click of text() button we are selecting this paragraph element, and using text() method we are updating its text.
0 comments:
Post a Comment