Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Nathan Marshall
Nathan Marshall
6,019 Points

The loop will not iterate through multiple tasks and give them the class of 'checked'

Hey Guys,

I'm currently building a 'To Do List App' using raw Javascript. I am currently experiencing a problem where I can not add my checked class to my newly appended tasks. I have tried using event delegation and I have tried to iterate through all of the tasks which I have stated with getElementsByClassName.

I have managed to get to the stage where I can add the class to the second task once added but not the first.

I am now at a dead end, I really wanted to do this without any help but I'd rather understand what I'm doing wrong at this point.

Here is my CodePen: https://codepen.io/Nathan-Callum-Marshall/pen/qKJPRV?editors=1010

Help/Guidance would be appreciated.

Thanks

4 Answers

Tristan Magpantay
seal-mask
.a{fill-rule:evenodd;}techdegree
Tristan Magpantay
Full Stack JavaScript Techdegree Student 14,032 Points

Hi Nathan,

in that case, try to put your add event listener declaration inside functions that you can call every time after you create new elements

Nathan Marshall
Nathan Marshall
6,019 Points

Thanks Tristan will do some more reasearch!

Balazs Peak
Balazs Peak
46,089 Points

I think the problem is that you are adding even-listeners at the beginning, and adding the tasks later, but the new tasks do not have the event listener.

What I would do is putting all tasks in a container, and setting up the listener at the beginning for the container: if the container got clicked, the clicked child element would get the specific actions, for example. (You can do that with the even target thing.)

Nathan Marshall
Nathan Marshall
6,019 Points

Hi Balazs,

Thanks for your feedback. I will have an experiment with what you have mentioned and see if I can get it to work.

Nathan Marshall
Nathan Marshall
6,019 Points

Hi Tristan,

I am aware of the jQuery method .on(). But I am challenging myself to try and do this without JQuery, as I have already built a todo list app with it already. I still haven't found a solution :/. I can see why everyone resorts to JQuery.