JavaScript JavaScript and the DOM Traversing the DOM Getting the First and Last Child

Don Page
Don Page
4,021 Points

Sharing the extra work I have done to improve this solution

// Creating a new button that accepts text to name the text and class name
function newButton(li, txt) {
  let button = document.createElement('button');
  button.className = txt;
  button.textContent = txt;
  li.appendChild(button);
}

// declaring the newButton function & using an array of button names.
// Would make it much easier to create new or remove existing buttons
function attachListItemButtons(li, name) {
  name = ['up', 'down', 'remove'];
  for(i = 0; i < name.length; i += 1) {
    newButton(li, name[i]);
  }
}

for(let i = 0; i < lis.length; i += 1) {
  attachListItemButtons(lis[i]);
}

3 Answers

Steven Parker
Steven Parker
203,753 Points

Nice refactoring! But I noticed that the "attachListItemButtons" function doesn't need the second argument:

function attachListItemButtons(li) {
  const name = ['up', 'down', 'remove'];
Don Page
Don Page
4,021 Points

Good spot! :) You're right, that second argument was left over from before I was pulling the button names from an array.

I love this! This is so clever. I kept trying to think of an easier way to add the buttons and I'm so glad someone figured it out.

Don Page
Don Page
4,021 Points

Glad it was useful Emma :)