Using jQuery text() Method
The text() method allows us assign or add plain text values. The method treats the contents as text. Here’s an example.
<html>
<head>
<title>jQuery text() Method Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<label id="lblName"></label>
</body>
<script>
$(document).ready(function () {
$('#lblName').text('Hello, I am Arun Banik');
});
</script>
</html>
Using jQuery html() Method
The html() method on the other hand, allows us to write HTML codes, along with the text (or any string value). Use this method when you want to add style to your text (or the entire sentence) or you want to add a link (<a>…</a>) with the text etc.
In the example below, I have added the <b>… </b> tags along with my name to show the value in bold.
<html>
<head>
<title>jQuery html() Method Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<label id="lblName"></label>
<script>
$(document).ready(function () {
$('#lblName').html('Hello, I am <b> Arun Banik </b>');
});
</script>
</body>
</html>
Note: If you add any markup or HTML code to the text() method, it will show the content along with the HTML codes, as it is. For example, if I want show what HTML codes were added to the content, I’ll do this.
$('#lblName').text('<u>Hello</u>, I am <b> Arun Banik </b>');
Output
<u>Hello</u>, I am <b> Arun Banik </b>
Or, you can use JavaScript methods like innerHTML and innerText to assign values to the labels, dynamically. It is simple, does not require any library, and hence improves the performance of your app on the web.