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,368 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);