The text() method as the name suggests, returns string that contains the text contents of all matched elements. This method can be applied for both HTML and XML documents.
Note : text() cannot be used for input elements. For input field text , we need to use the val() method.
It is also used to Set the text contents of all matched elements.
$(“#ddlID”).text() – gets text of all the items inside the dropdown id ddlID
$(“.classdefine”).text() = gets text of all elements with clas classdefine
$("p").text() – gets text inside element Paragraph. It can be same applied to all elements except input text field.
Here is the sample that explains it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var str = $("p:first").text();
$("p:last").html(str);
});
</script>
<style>
p { color:blue; margin:8px; }
b { color:red; }
</style>
</head>
<body>
<p><b>Test</b> Paragraph.</p>
<p></p>
</body>
</html>
This gets text inside an element <b>.
text(val ) method
The text value to set the contents of the element to.
<script>
$(document).ready(function(){ $("p").text("<I>Some</I> test text."); });
</script>
val() method
jQuery API contains val() method that returns value of any element.
$(“#txtName”).val() - gets the value inside the textbox. This can also be sued to set value to the element
for ex: $('#<%=txtFirstName.ClientID %>').val() =”some value ” is used to set the value to the ASP.NET text box.
This value can be used for the validation or checking against data at client or server side.