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

Ken Okiebisu
Ken Okiebisu
9,673 Points

Appending and Prepending

I have this question where I have to create a new li element containing the student name "Sam Smith", and saving it to a variable called $newStudent.

I wrote the code like the following:

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

I keep getting an error from it. What is wrong with my code and how can I fix this problem? Thanks in advance!

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2>Student List</h2>

    <ul class="student-list">
        <li>James McAvoy</li>
        <li>Alena Holligan</li>
        <li>Wade Christensen</li>
        <li>Matt Krzyzynski</li>
    </ul>

    <script
    src="jquery-3.2.1.min.js"></script>
    <script src="app.js"></script>
</body>
</html>
app.js
 var $newStudent = $(".student-list").append("<li>Sam Smith</li>");

1 Answer

Louise St. Germain
Louise St. Germain
19,424 Points

Hi Ken,

There's nothing wrong with the syntax of your code, but it's not quite doing what the challenge is asking. The challenge doesn't need you to append your new element to the list. You literally just need to create the new element and assign it to the $newStudent variable.

So the question is simpler than you think! I hope this helps!

I'd say given what what taught in the preceeding video, that question is very poorly worded. I spent a fair amount of time thinking I'm typing in incorrect JS/Jquery. Especially since the very next question has us do it anyway. Not to mention the way its taught you would use the '$' in a variable name if the content of the variable contained JQuery. This one doesn't, its just a list.

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

// Wouldn't that have also worded just fine as ?

const newStudent = "<li>SamSmith</li>";

$(".student-list").append(newStudent);