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 trialHamzah Iqbal
Full Stack JavaScript Techdegree Student 329 PointsCode 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.
e.preventDefault();
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
Treehouse Moderator 91,252 Pointsconst 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. :)