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 trialDaniel McHugh
1,821 PointsCan someone walk me through exactly what we did here in terms of what caused what?
Okay, so the "span" tag is just a tag to convert a text element to an html element.
ul.addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
const button = e.target;
const li = button.parentNode;
const ul = li.parentNode;
if (button.textContent === 'remove') {
ul.removeChild (li);
} else if (e.target.textContent === 'edit') {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
} else if (e.target.textContent === 'save') {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
}
});
Where it loses me is here. what does this piece of code do?
const span = li.firstElementChild;
And these pieces are also confusing to me.
li.insertBefore(input, span);
li.removeChild(span);
Is it effectively putting the new input and removing the old one? What is the span tag doing in each of these?
And what does reversing these lines of code do?
span.textContent = input.value;
li.insertBefore(span, input);
1 Answer
Steven Parker
231,248 PointsIt seems like you have the right idea already, but perhaps this will make it a bit more clear:
const span = li.firstElementChild;
gets the first element inside the "li" (probably a "span" )
You were right about these lines putting in the new "input" and removing the old "span":
li.insertBefore(input, span);
put the new "input" in front of the "span" element already there
li.removeChild(span);
then, the "span" element is removed from the document
And as you expected, these other lines do just the reverse by adding a new "span" and removing the "input":
span.textContent = input.value;
copy the text from the "input" into the new "span"
li.insertBefore(span, input);
then put the new "span" in front of the old "input"
li.removeChild(input);
finally, delete the "input"
Nathan Angulo
4,565 PointsNathan Angulo
4,565 PointsCould li.appendChild(span) work instead of li.insertBefore()???
Steven Parker
231,248 PointsSteven Parker
231,248 PointsIt would add it, but it would appear in a different place (at the end).