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.