When to use jQuery.html or .text for an element

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

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

or

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

Is another preferable? Are there differences in performance or is one of the methods not working and the other in special situations?

+8
performance jquery
source share
3 answers

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

In fact, both look somewhat similar, but completely different, it depends on your use or intention, what you want to achieve,

Where to use:

  • use .html () to work with containers with html elements.
  • use .text () to change the text of elements that usually have separate open and close tags

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

Unlike the .html (),. Text () method 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 HTML parsers in different browsers, the returned text may change in new characters and other empty space.)

+5
source share

Data setting

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

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

Reading data

.text() will only return text nodes (descriptors)

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


Here's a JSFiddle that shows the difference in both directions.

+20
source share

If HTML does not have HTML labels, then this is one and the same thing, but if there is (for example, a red "necessary" label), it would be advisable to use .text() so that you just get that label and not the HTML that generates it.

+5
source share

All Articles