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

JavaScript jQuery Basics Understanding jQuery Events and DOM Traversal Using on() for Event Handling

Roger Hwang
Roger Hwang
3,851 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,851 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.