0

I have created a form to search for things and added them as div in the container. Now for every new search I want all the divs from the container to be removed. How do I do that?

const container = document.querySelector('.container');
const form = document.querySelector('#search-form');
form.addEventListener('submit', async function(e) {
  e.preventDefault();
  clear();
  const searchTerm = form.elements.query.value;

  const config = {
    params: {
      q: searchTerm
    }
  }
  const res = await axios.get(`http://api.tvmaze.com/search/shows`, config);
  displayShows(res.data);

  form.elements.query.value = '';
})

function clear() {
  for (div in container) {
    div.remove();
  }
}
<form id="search-form">
  <input type="text" placeholder="TV Show Title" name="query">
  <button id="search-btn">Search</button>
</form>

<div class="container">
  <div>Here is div-01</div>
  <div>Here is div-02</div>
  <div>Here is div-03</div>
</div>
VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

0

If you want to remove all the divs in the container (assuming that you are generating each of them again upon running displayShows()):

In place of clear(), do this:

container.innerHTML = ''

This will remove everything inside the container div, including the tags.

Isaac Yong
  • 109
  • 1
  • 5
0

You can remove your divs using something like this below

  var e = document.getElementById("you_might_want_a_unique_id");
  var divs = e.querySelectorAll("div");
  for(var i=0;i < divs.length;i ++)
    e.removeChild(divs[i]);    

Just add an id attribute to your container (incase your have multiple containers)

<div id="you_might_want_a_unique_id" class="container">
Niraeth
  • 315
  • 2
  • 4