简体   繁体   中英

How can i remove previous searched items on next search

Getting images of all the movies starting with what user searched for just want to remove previous images on every next search how can i do that

<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport"     content="width=device-width, initial-  scale=1.0">
<title>TV Show Search</title>

<script     src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>

<body>
<h1>TV Show Search</h1>
<form id="searchForm">
    <input type="text" placeholder="TV Show Title" name="query">
    <button>Search</button>
</form>
<script src="app.js"></script>
</body>

</html>

JavaScript Starts From Here

const form =   document.querySelector('#searchForm');

Added an eventlistener on form.

form.addEventListener('submit', async     function (e) {
e.preventDefault();
const searchTerm =     form.elements.query.value;
const config = { params: { q:    searchTerm } }
var res = await     axios.get(`http://api.tvmaze.com/search/shows`, config);

Getting results from an api

makeImages(res.data)
form.elements.query.value = '';

})



const makeImages = (shows) => {
for (let result of shows) {
    if (result.show.image) {
        const img =    document.createElement('IMG');
           img.src=result.show.image.medium;
        document.body.append(img)
    }
}
}

How can i remove previous images on next search

The easiest way would probably be to remove all children, that is clear the element's innerHTML . To avoid messing up the rest of the page, consider moving your images to a separate <div> :

html:

<!-- ... -->
</form>
<div id="resultImages"></div>
<script src="app.js"></script>
<!-- ... -->

js:

const resultImagesDiv = document.getElementById('resultImages');

const makeImages = (shows) => {
  resultImagesDiv.innerHTML = ''; // Clear all previous images
  for (let result of shows) {
    if (result.show.image) {
      const img = document.createElement("img");
      img.src = result.show.image.medium;
      resultImagesDiv.appendChild(img);
    }
  }
};

For more details on how to remove all children of an Html element, see this question .

resultImagesDiv.innerHtml = ''; - This is wrong. It should be innerText instead.

resultImagesDiv.innerText = '';

I'm assuming this is for a certain online bootcamp video on Udemy. If so, everyone that finds this should have the solution for the extra credit part he doesn't give the answer to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM