8

In this question that I posted (and was answered), I found out how to properly assign the value of a textbox to the value of a label. The answer was to use either

$('#txtBranchName').val($('#lblBranchName').html());

or

$('#txtBranchName').val($('#lblBranchName').text());

Is one preferable over the other? Are there performance differences, or would one method not work but the other would in particular situations?

Community
  • 1
  • 1
marky
  • 4,878
  • 17
  • 59
  • 103
  • related http://stackoverflow.com/questions/1910794/what-is-the-difference-between-jquery-text-and-html – Adriano Dec 16 '14 at 14:10

3 Answers3

20

Setting data

.text("<b>Test</b>") will escape any HTML tags (rendering <b>Test</b>)

.html("<b>Test</b>") will render them as actual HTML elements (rendering Test).

Reading data

.text() will return text nodes only (stripping tags)

.html() will return actual HTML string including tags.


Here's a JSFiddle that shows the difference both ways.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
5

If there are no HTML children of the label, then it's the same either way, however if there are any (such as a red "required" mark) it would be preferably to use .text() so you just get that mark rather than the HTML generating it.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
5

Refer : What is the difference between jQuery: text() and html() ? and Differences between .text() and .html() with escaped < and > characters

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

Where to use:

  • use .html() to operate on containers having html elements.
  • use .text() to modify text of elements usually having separate open and closing tags

jQuery.html() treats the string as HTML, jQuery.text() treats the content as text.

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75