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

Why does using two standalone 'if' statements not work, while using two 'if' statements nested within another 'if' does?

I went ahead and tried to solve the challenge ahead of the video and came up with this solution. The first 'if' statement works, and clicking the remove button does remove the li. However, when I click the 'up' button, the li doesn't move up in the list as anticipated. Here is my code:

toggleList.addEventListener('click', (event) => {
    let element = event.target;
    if (element.tagName == 'BUTTON' && element.className == 'remove') {
        let li = element.parentNode;
        let ul = li.parentNode;
        ul.removeChild(li);
    }
    if (element.tagname == 'BUTTON' && element.className == 'up') {
        let li = element.parentNode;
        let previousLi = li.previousElementSibling;
        let ul = li.parentNode;
        ul.insertBefore(li, previousLi);
    }
});

I've already got the code working doing it the same way Guil did in the video, where there are two 'if' statements that test the class names separately within a wrapping conditional that tests whether the tag name is equal to BUTTON, but I want to know why my previous approach doesn't work. (And why it does work for the remove button)

Any ideas?

1 Answer

Steven Parker
Steven Parker
243,656 Points

You just have a typo.

In the second if, you wrote "tagname" (with a lower-case "n") instead of "tagName" (with a capital "N").

Also, your first if block should end with a return, since otherwise the second if will be attempting to test an element which no longer exists.

Thanks Steven! Typos FTW. And I agree, adding a return statement makes sense.