JavaScript JavaScript and the DOM Making Changes to the DOM Appending Nodes

Found a little bug in the code with changing description and adding to the list.

If a User clicks the 'Change Description List' button, it will replace the description with 'blank': If a User clicks the 'Add Item' button, it will add a blank list item.

I fixed it in my code by adding conditions to both addEventListerner functions.

// Add variables to change description based on user's input
const descriptionP = document.querySelector('p.description');
const descriptionInput = document.querySelector('input.description');
const descriptionButton = document.querySelector('button.description');

// This is the function to change the description based on user's input
descriptionButton.addEventListener('click', () => {
  if (descriptionInput.value === '') {
    alert("You must enter a change list description");
  } else {
      descriptionP.textContent = descriptionInput.value + ':';
      descriptionP.style.color = 'red';
      descriptionInput.value = ''; 
    } 
});

// Add variables to add a list item based on user's input
const userInput = document.querySelector('input.addItemInput');
const inputButton = document.querySelector('button.addItemButton');

// This is the function to create a new list item dynamically based on user's input
inputButton.addEventListener('click', () => {
  if (userInput.value === '')  {
    alert("You must enter a change list description");
  } else {
      let ul = document.getElementsByTagName('ul')[0];
      let li = document.createElement('li');
      li.textContent = userInput.value;
      ul.appendChild(li);
      userInput.value = '';
    }
});

1 Answer

Steven Parker
Steven Parker
171,314 Points

I'm not sure if I'd say the original code had a "bug", but your modification of adding input validation is a nice enhancement. :+1:

Thank you.