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 Understanding jQuery Events and DOM Traversal Using on() for Event Handling

Roger Hwang
Roger Hwang
3,850 Points

Create and add new element to HTML

When adding a new element to the DOM, why do we need to put the newly created element inside "$()" since we aren't trying to select an element from the DOM? One of the exercises passed only when including the "$()" but I tried without it and the new element was still added to the DOM.

Why is the list item wrapped in "$()"?

const $newStudent = $('<li>Sam Smith</li>');
$('.student-list').append($newStudent);

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi Roger,

I know what you are saying and the only reason you would make it a jQuery element (by wrapping in "$()") is if you were wanting to do something with it. Treehouse usually does it like this to teach good practices and expand your knowledge in how to do things. They also promote experimentation to help you understand whats going on.

This would work fine if you were happy with it as is:

$('.student-list').append('<li>Sam Smith</li>');

I usually wrap the elements because I'm doing other things with them, which I have shown in the example below. But it is good to learn multiple ways of doing the same thing as you will come across other peoples code and have to understand what's happening.

const $newStudent = $('<li>Sam Smith</li>');
$newStudent.click(function() {
  alert('Add student : '+$(this).text());
});
$('.student-list').append($newStudent);
Roger Hwang
Roger Hwang
3,850 Points

Cool. Thanks for the explanation. I always thought "$()" was used only when you want to target an element but apparently it can be left on an element and not really do anything per my example.