How/When 删除子元素以清除搜索结果?

How/When to remove child elements to clear search result?

在我提交新的 API 调用后试图清除我的搜索结果。尝试在不同点实施 gallery.remove(galleryItems); 但无济于事。

有点失望我想不通,但很高兴我能够运行一些异步函数。无论如何,这是代码:

'use strict';

const form = document.querySelector('#searchForm');
const gallery = document.querySelector('.flexbox-container');
const galleryItems = document.getElementsByClassName('flexbox-item');

form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const userSearch = form.elements.query.value;   // grab user input
    const res = await getRequest(userSearch); // async func that returns a fully parsed Promise
    tvShowMatches(res.data); // looks for matches, creates and appends name + image;
    form.elements.query.value = '';
});

const getRequest = async (search) => {
    const config = { params: { q: search } };
    const res = await axios.get('http://api.tvmaze.com/search/shows', config);
    return res;
};

const tvShowMatches = async (shows) => {
    for (let result of shows) {
        if (result.show.image) {
            // new div w/ flexbox-item class + append to gallery
            const tvShowMatch = document.createElement('DIV')
            tvShowMatch.classList.add('flexbox-item');
            gallery.append(tvShowMatch);

            // create, fill & append tvShowName to tvShowMatch
            const tvShowName = document.createElement('P');
            tvShowName.textContent = result.show.name;
            tvShowMatch.append(tvShowName);

            // create, fill & append tvShowImg to tvShowMatch
            const tvShowImg = document.createElement('IMG');
            tvShowImg.src = result.show.image.medium;
            tvShowMatch.append(tvShowImg);
        }
    }
};

谢谢

考虑在 submit 事件发生时将 gallery.innerHTML 重置为空字符串,而不是 gallery.remove(galleryItems);

像这样:

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  gallery.innerHTML = ''; // Reset here
  const userSearch = form.elements.query.value;   // grab user input
  const res = await getRequest(userSearch); // async func that returns a fully parsed Promise
  tvShowMatches(res.data); // looks for matches, creates and appends name + image;
  form.elements.query.value = '';
});

我相信这会成功..你很接近。

const galleryItems = document.getElementsByClassName('flexbox-item');

// to remove
galleryItems.forEach(elem => elem.remove() );