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 trialevanritscher
10,209 PointsWhy does .text go between the opening and closing option tags>
In the video, the variable $option
is initially set to <option></option>.
Later we use .text to add the content in the anchor tag to the variable $option.
Why does adding .text put the content of the anchor tag in between the <option>
tags and not at the end of it or even replace it?
$('menu a').each(fucntion)(){
var $anchor =$(this);
var $option = $('<option></option');
$option.text($anchor.text()); });
1 Answer
John Coolidge
12,614 Points.text() takes the jQuery wrapped DOM element, in this case $(<option></option>), and inserts inside of it whatever text you choose to put there. Under the hood, jQuery knows that when we use the .text() method, we specifically want to alter the text of the option element, not replace the element itself, or place the text anywhere but inside the element. You can't use the .text() method to do anything else but add text inside an element.
You can do the same thing in plain old JavaScript too. In both cases, JavaScript and jQuery both know that the method we are invoking is simply adding text inside the DOM element.
evanritscher
10,209 Pointsevanritscher
10,209 PointsSo basically, it just figures it out on it's own.
John Coolidge, in plain old JavaScript what would do this? As I understand it += would add the content to the end.
John Coolidge
12,614 PointsJohn Coolidge
12,614 PointsThis is one of those topics that comes with a lot of baggage. You can search the interwebs looking up .innerText vs .innerHTML vs. .textContent, etc. I say that because you might run across various ways to insert text inside a DOM element while searching online. There are many. They all have their problems, and browser differences are the culprits.
What .text() in jQuery does (roughly) is find out what browser you're using and uses the appropriate method that best fits your browser. Thank goodness jQuery does all the heavy lifting in this case. :)
Now, to answer your question: As I understand it, the best way to insert text so that you maximize cross-browser compatibility in vanilla JavaScript is to use .innerHTML(). Some folks may disagree with that for various reasons. That's okay. Hopefully in the future we have one cross-browser method of inserting text into a DOM element. I hope that helps.