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 trial

JavaScript Using jQuery Plugins Add a Sticky Navigation Bar Understanding Plugin Events

Andreas Kratzel
Andreas Kratzel
2,858 Points

Difference 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!

Andreas Kratzel
Andreas Kratzel
2,858 Points

Okay 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?

3 Answers

Steven Parker
Steven Parker
231,269 Points

:point_right: It'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
Andreas Kratzel
2,858 Points

What exactly do you mean with the security issue regarding the .html()-method?

Hey 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.

Hey 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
Steven Parker
231,269 Points

It'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.