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 trialMarni Ali
4,642 PointsHow do you prepend attr() for checkbox input in .each method?
With this objective exercise, I have a problem using .attr for input with checkbox type. I am able to use the .each method, however, it displays (undefined) prepending the list from the 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>
$('.favorite-things li').each(function() {
const checkbox = $(this).attr('checked');
$(this).prepend(`(${checkbox})`);
});
2 Answers
Steven Parker
231,269 PointsThere isn't anything on the page that could be in a "checked" state before the code runs. Plus, the string that the instructions tell you to add can be used verbatim in your code so you don't need to select anything from the existing page code.
Marni Ali
4,642 PointsI see, Thanks Steven.
Is that allowed because there are no arguments in the function of .each?
Steven Parker
231,269 PointsThe fact that "attr" isn't needed here is not related to using arguments in .each
(or not).
The function in .each
can take one or two arguments, but this challenge asked you to create a solution without using them.. For more details, see the jQuery documentation page on .each().
Marni Ali
4,642 PointsMarni Ali
4,642 PointsHi Steven, Thanks for the reply. But unfortunately, I am not getting what you are saying. This is my understanding so far, to add the string in the .attr() as such:
Steven Parker
231,269 PointsSteven Parker
231,269 PointsWhat I was saying is that you don't need "attr" at all, and don't need to create a new variable.
You can just prepend the string directly:
$(this).prepend('<input type="checkbox"/>');