Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndreas Kratzel
2,858 PointsDifference of .text() and .html()
Hi there,
I've tested this code and this works perfectly fine as well as the .html()-version from Dave:
$(".header").on("sticky-start", function() {
$(".description").text("we build great apps");
});
Can someone tell me the difference or why Dave is using the .html()-method in this example?
Thanks!
3 Answers
Steven Parker
231,236 PointsIt's a trade-off between security and versatility.
Both methods will replace plain text. The .html method will also do element tags and attributes, but at the cost of creating a potential security issue it the new content source comes directly or indirectly from user input.
Andreas Kratzel
2,858 PointsWhat exactly do you mean with the security issue regarding the .html()-method?
Stephen Van Delinder
21,457 PointsHey Andreas,
The major difference is that the .text()
method will display html, while the .html()
method will render html. Ideally, you'd want to make a habit of escaping your inputs, so users never insert code that is rendered or otherwise executed by your applications.
Here's a JSFiddle for further clarification.
Hope this helps.
Andreas Kratzel
2,858 PointsThanks!
nfs
35,526 PointsHey Steven Parker, and Stephen Van Delinder,
I want to know more about the "trade-off between security and versatility." Can you please elaborate on that? or direct to a helpful resource or something like that? Thanks in advance.
Steven Parker
231,236 PointsIt's just that text will just be shown by the browser, but html is acted on by the browser. So while you can do more using html, it's also possible that something undesired could be done also unless special precautions are taken.
Andreas Kratzel
2,858 PointsAndreas Kratzel
2,858 PointsOkay I have figured it out myself - you can't add HTML-tags like <b> or something like that with the .text()-method. :) I guess that's the biggest advantage, isn't it?