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 trialRyan Broughan
12,742 PointsIs 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
27,419 PointsHi 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 '<' and '>'), 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"><p>Example text</p></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
26,676 PointsHi 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.
Stephen Wisner
4,893 PointsThanks for answering my question as well!