Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 238
marky Avatar asked Jan 24 '13 15:01

marky


People also ask

What is difference between HTML and text in jQuery?

text() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected.

What does .text in jQuery do?

The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.

What is the use of .HTML in jQuery?

html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

Why jQuery is not recommended?

Back to the topic at hand on Why You shouldn't use JQuery in a framework? Because it'll just make your app heavy. Everything JQuery can do, VanillaJS/JS/TypeScript can do better and faster. It results to a terribly large amount of JavaScript code written.


1 Answers

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.

like image 60
Robert Koritnik Avatar answered Oct 12 '22 00:10

Robert Koritnik