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 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!