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.


Code working but not understanding the code

So the following code Is working. However im confused in terms of, what is happening.

const form = document.getElementById("registrar"); //We get the element id "registrar
const input = form.querySelector("input"); // its a form and understands that it has to save, whatever is entered into "input"

form.addEventListener("submit", (e) => { //There is a even listener added, that is a method called submit, it is than told that (e) has to do the following function.

const text = input.value; //we store the inputted value in text.
const ul = document.getElementById("invitedList"); // we get the element by ID of the invited list
const li = document.createElement("li"); // Why do we create li?
  li.textContent = text; // What is textContent
 ul.appendChild(li);   //why do we appenChild to ul ? what is the purpose of Li                            

1 Answer

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,028 Points
const li = document.createElement("li"); // A list item is a child or a list.
  li.textContent = text; // Gets the text content of a given element.
 ul.appendChild(li);   //The append child method is what adds elements to the not, not createElement.   

So, what's happening is you're getting a reference to the list element (an ordered or an unordered list) so JavaScript knows which element to perform actions on. What you're trying to do here is add a task, or item as a list item (which is of course an <li> a list item.

const li is just what you're naming the attempt to create a list item. the createElement method prepares the DOM to recieve new nodes.

li.textContent grabs the content of the list item. There's a similar one called innerHTML but we're only interested in the text and nothing else.

You've already selected your list ul and written the code to create a new list item. But nothing will happen until you instruct the DOM to add a new node or instance of the element you want to create, which is your list item. i.e. const li.

Hope this makes sense. :)