Bummer! You have been redirected as the page you requested could not be found.

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

Greg Schudel
Greg Schudel
4,090 Points

Questions Javascript Function code

I'm surprized it takes line four lines of code to do something behind the scenes with Javascript. How does the function know where I want to place the element in my app? Why do I need to create an element called input, can't it just be a div?

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

const ul = document.getElementById('invitedList'); // creates element ul

form.addEventListener('submit', (e) => {

  // prevents it  
  e.preventDefault();

  // creates it
  const text= input.value;
  input.value = ''; //clears it
  const li = document.createElement('li'); 


  // checkbox
  const label = document.createElement('label'); // creates element and names it label
  label.textContent = 'Confirmed'; // creates words for that label called 'confirmed' how does it know where to place it in the dom?
  const checkbox = document.createElement('input'); // creates an input? why do I need this?
  checkbox.type = 'checkbox'; // changes the element to be a checkbox.

  //converts it
  li.textContent = text;

  //appends checkbox
  label.appendChild(checkbox);

  // appends ul
  li.appendChild(label);
  ul.appendChild(li);


});

1 Answer

Steven Parker
Steven Parker
231,269 Points

The function knows where to place the new element when you perform these statements:

  li.appendChild(label);  // place the label inside the new list item
  ul.appendChild(li);     // place the new list item at the end of the unordered list

And the reason to create a new "input" element is that will be a functioning check box on the page. A "div" element would not look or act like a check box (at least not without a lot of styling and scripting).