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 DOM Scripting By Example Adding and Removing Names RSVP Checkbox

Ryan Schmelter
Ryan Schmelter
9,710 Points

Confused about how the code in executing in this order.

In the event handler, the code runs in order from top to bottom - right? It seems like appending the checkbox to the label would throw an error since, at that point, the label is not itself yet appended. Any clarification would be appreciated.

`` const form = document.getElementById('registrar'); const input = form.querySelector('input');

form.addEventListener('submit', (e) => { e.preventDefault(); const text = input.value; input.value = ''; const ul = document.getElementById('invitedList'); const li = document.createElement('li'); li.textContent = text; const label = document.createElement('label'); label.textContent = 'Confirmed'; const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; label.appendChild(checkbox); ul.appendChild(li); li.appendChild(label);

})

``

2 Answers

Bruno Navarrete
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,246 Points

The label element exists from the moment you document.createElement() it so you can append to it, define it's innerHTML or even delete it from then on. In this case, you create everything and then nest it in the end because it is easier to manage individual elements.

Node.appendChild() adds a node(e.g checkbox) after the last child node of the specific element node(e.g label)

Like what Bruno said, Document.createElement() creates the HTML element by tagName.

`label' is a native element in the browser, that we can use to create our label element.

const label = document.createElement('label'); 

At this assignment const label will be defined within the scope of the function.

Next we create the create the checkbox element

const checkbox = document.createElement('input');
checkbox.type = 'checkbox';

At this assignment const checkbox is now defined. Since our label element has already been created at this point. We are able to append to the newly createdcheckbox element to the label without it needing to be appended to the li element

I hope this helps.