JavaScript jQuery Basics Working with jQuery Collections The .each() method

Christine Bogdan
Christine Bogdan
5,339 Points

question about "this" in each() method

Hi there!

This is the task:

Inside the jQuery each() method, use prepend() to add an '<input type="checkbox"/>' to the beginning of each list item. Use the this keyword, so the callback function doesn't need any arguments.

I tried this:

$('.favorite-things li').each(function() {
  this.prepend("<input type='checkbox'/>");
});

It's giving me an error message, and I cannot figure out why.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h2>My Favorite Things</h2>

    <ul class="favorite-things">
        <li>Kittens</li>
        <li>Rainbows</li>
        <li>Unicorns</li>
        <li>Sprinkles</li>
    </ul>

    <script
    src="jquery-3.2.1.min.js"></script>
    <script src="app.js"></script>
</body>
</html>
app.js
$('.favorite-things li').each(function() {
  this.prepend("<input type='checkbox'/>");
});

2 Answers

Christine Bogdan
Christine Bogdan
5,339 Points

Hi Gabriel Pierce-Lackey, can't believe I missed that. Have been looking at it all afternoon. Thanks!