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

CSS jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 4

Is there any reason to use .text() over .append()?

I initially added the text to the caption with .append(), which totally works. Is there an advantage to using .text() in similar instances? Or was Andrew just trying to show us a new method?

2 Answers

Damien Watson
Damien Watson
27,419 Points

Hi Ryan,

Both jQuery $.text() & $.html() replace the contents of the element, where $.append() & $prepend() add to the content.

If you have a string say '<span>Example text</span>', $.text() will display all characters (including '&lt;' and '&gt;'), rather than creating a new element. The other 3 create and elements inside the string.

<!-- example html targets -->
<div id="div1">Content:</div>
<div id="div2">Content:</div>
<div id="div3">Content:</div>
<div id="div4">Content:</div>
$("#div1").text("<span>Example text</span>");
// output -->  <div id="div1">&lt;p&gt;Example text&lt;/p&gt;</div>

$("#div2").html("<span>Example text</span>");
// output -->  <div id="div2"><span>Example text</span></div>

$("#div3").append("<span>Example text</span>");
// output -->  <div id="div3">Content:<span>Example text</span></div>

$("#div4").prepend("<span>Example text</span>");
// output -->  <div id="div3"><span>Example text</span>Content:</div>
Chris Shaw
Chris Shaw
26,676 Points

Hi Ryan,

With best practice in mind it's better to use append only when adding new elements to the DOM or moving existing elements around, text in general is really only designed for, well, text. Just so my judgement isn't clouded by any bias I decided to run a test with jsPerf to try and see which made the top spot.

http://jsperf.com/jquery-text-vs-append

Surprisingly in Chrome and Firefox append came out considerably faster but in Internet Explorer text took the top spot as I assume it's using a newer JavaScript implementation for innerText which is the sister to innerHTML, of course these tests are only as accurate as the browser is fast therefore there's no reason to use append just because it's faster.

As I said, under general circumstances it's better to use text and append for only what they do best, but again that is just my personal stance on it as I couldn't find any articles relating to the question.

Hope that helps.

Thanks for answering my question as well!