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 Adding New Elements to the DOM

Liam Hayes
Liam Hayes
Full Stack JavaScript Techdegree Student 13,116 Points

What does it mean when I do this with JQuery? const newStudent = $('<li>Sam Smith</li>');

Hi there :)

If I type this in a project javascript's file

var newStudent = $('<li>Sam Smith</li>'); 

What does this accomplish? (By the way, when I type that there is not already a Sam Smith list item in the HTML already. I'm typing a new list item, not trying to select one from the HTML file).

Thank you very much :)

2 Answers

Exactly. Instead of selecting an element from the DOM, you are creating a new list item element and initializing it as a jQuery object, allowing you to use any jQuery functions on the "newStudent" variable. You should then be able to do actions like:


to achieve

<li class="name-in-red">Sam Smith</li>

All before adding it to the DOM, i.e.:

$('ul').append(newStudent);  // add  the list item to (the end of) the <ul> tag

Example: https://jsbin.com/socoqiwume/edit?html,js,output

You are welcome Liam!