skip to Main Content

I’ve written a simple code that takes text from the input field, stores it as a string in an array and creates a div with that same text every time the "add" button is pressed.

Then there’s a "remove" button, that removes the item from array if the input matches the item in the array.

I need a function to remove the previously created div with the same text inside as the current input.

E.g. if I type "book1" press "add" – array gets ‘book1’ as a first item and a div "book1" is created, "book2", "book3" and so on. If I type ‘book2’ and press remove, it gets removed from the array and a respective div should be removed.

That last function I just can’t figure out.

let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
let innerDiv = document.body.newDiv.innerHTML

function addBook() {
  newBook = document.getElementById("input").value;
  if (newBook != '') {
    bookArray.push(newBook);
    addElement();
    clear();
    console.log(bookArray);
  } else {
    clear();

    console.log(bookArray);
  }
}

function removeBook() {
  inputBook = document.getElementById("input").value;
  for (i = 0; i < bookArray.length; i++) {
    if (inputBook.toString() === bookArray[i].toString()) {
      bookArray.splice([i], 1);
      console.log(bookArray);
      removeElement()
      return;
    } else {
      clear();
    }
  }
  console.log(bookArray);
}

function clear() {
  document.getElementById("input").value = "";
}

function addElement() {
  let newDiv = document.createElement("div");
  newDiv.innerHTML = newBook;

  my_div = document.getElementById("mydiv");
  document.body.appendChild(newDiv, my_div);
}

function removeElement() { 
   alert("this bit needs working out");//???
}
<input type="text" id="input" />
<button id="add-btn">Add</button>
<button id="rmv-btn">Remove</button>
<div id="mydiv"></div>
</div>

2

Answers


  1. A workaround to remove book by the input value by user:

    Modify the addElement function to:

    function addElement() {
      let newDiv = document.createElement("div");
      newDiv.innerHTML = newBook;
      newDiv.setAttribute('data-book-name', newBook); //new added line | setting data attribute
    
      my_div = document.getElementById("mydiv");
      document.body.appendChild(newDiv, my_div);
    }
    

    removeElement will be:

    function removeElement() { 
       document.querySelector('[data-book-name="'+ newBook +'"]')?.remove();
    }
    

    But this will remove first book in the DOM. If you want to remove all books with same name use:

    function removeElement() { 
       var books = document.querySelectorAll('[data-book-name="'+ newBook +'"]');
       if(books.length == 0) return;
       books.forEach(x => x.remove())
    }
    
    Login or Signup to reply.
  2. You need to change how you are adding the div because it adding it outside and not as a child of my_div

    let addBtn = document.getElementById("add-btn");
        let removeBtn = document.getElementById("rmv-btn");
        let bookArray = [];
        addBtn.addEventListener("click", addBook);
        removeBtn.addEventListener("click", removeBook);
        
        
        function addBook() {
          newBook = document.getElementById("input").value;
          if (newBook != '') {
            bookArray.push(newBook);
            addElement();
            clear();
            console.log(bookArray);
          } else {
            clear();
        
            console.log(bookArray);
          }
        }
        
        function removeBook() {
          inputBook = document.getElementById("input").value;
          for (i = 0; i < bookArray.length; i++) {
            if (inputBook.toString() === bookArray[i].toString()) {
              bookArray.splice([i], 1);
              console.log(bookArray);
              removeElement(i);
              return;
            } else {
              clear();
            }
          }
          console.log(bookArray);
        }
        
        function clear() {
          document.getElementById("input").value = "";
        }
        
        function addElement() {    
          let newDiv = document.createElement("div");
          // count number of children in mydiv
          let count = document.getElementById("mydiv").childElementCount;
        
          // add an id
        
          newDiv.id = 'mydiv-' + count;
          newDiv.innerHTML = newBook;
        
          my_div = document.getElementById("mydiv");
          my_div.appendChild(newDiv, my_div);
        }
        
        function removeElement(el) { 
           // remove html element from dom
            let my_div = document.getElementById("mydiv");
            my_div.removeChild(my_div.childNodes[el]);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search