Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 3

Ryan Atkins
Ryan Atkins
8,635 Points

Why not a string instead of JQuery object?

I probably should have asked this in an earlier section, but why are we assigning a string within $() instead of just assigning a normal JS var to the string we want and then pass that JS var into .append()? Like this:

var typicalVar = '<div id="typicalID"></div>'; $("body").append(typicalVar);

I'm guessing the "$()" around it makes it a JQuery object and .append() can only take JQuery objects? Not sure and would like clarification.

3 Answers

Hey Ryan,

The append() function appends elements, strings, or other values to the element specified, not necessarily just jQuery objects. You can append any kind of element to practically any other kind of element.

Here's an example where I create a variable that creates a new element, and I append it to the body. It can be created with jQuery or plain JS and then appended using jQuery like so:

//Plain JS
/*
var newel = document.createElement("p");
newel.textContent = "Hey there!";
*/
//jQuery
var newel = $("<p>Hey there!</p>");
$("body").append(newel);

For more information, check out the jQuery append article: http://api.jquery.com/append/

Ryan Atkins
Ryan Atkins
8,635 Points

But can you do this:

var newel = "<p>Hey there!</p>";
$("body").append(newel);

A mix and match of plain JS with JQuery.

Yes, you sure can, but you have to keep in mind that you can't apply anything else to that new element like you can with a jQuery object or with the create element in plain JavaScript. What this means is that you can literally apply what is within the string, but you won't be able to manipulate newel beyond that, which is why it isn't a good practice to create elements this way.

Ryan Atkins
Ryan Atkins
8,635 Points

Very cool. Thank you for the thorough explanation.

No problem, man. Happy Coding!