I have a search function on my site that takes a text input and searches "documents" for a matching string of text, then displays the matching items in a list. This works perfectly. I just need a way to limit the number of list items that can be appended to the list. For example, if there are 4 matching results, then I only want 2 to be displayed.
const documents = [
{ id: 1, innerHTML: "<a data-name='Princess' href='/The_Princess'>The Princess</a>" },
{ id: 2, innerHTML: "<a data-name='Player' href='/The_Player'>The Player</a>" },
{ id: 3, innerHTML: "<a data-name='Narrator' href='/The_Narrator'>The Narrator</a>" },
{ id: 4, innerHTML: "<a data-name='Vessel Adversary' href='/Vessel/Adversary'>Vessel: Adversary</a>" },
];
function performSearch() {
const query = document.getElementById('searchBox').value.toLowerCase();
const results = search(query);
displayResults(results);
}
function search(query) {
return documents.filter(doc => doc.innerHTML.toLowerCase().includes(query));
}
function displayResults(results) {
const resultsElement = document.getElementById('results');
resultsElement.innerHTML = '';
results.forEach(result => {
const listItem = document.createElement('li');
listItem.innerHTML = result.innerHTML;
resultsElement.appendChild(listItem);
});
}
<input type="text" id="searchBox" placeholder="Search...">
<button onclick="performSearch()">Search</button>
<ul id="results"></ul>
I've tried using listItem.slice(0, 2), innerHTML.slice(0, 2), listItem.innerHTML.slice(0, 2), and resultsElement.slice(0, 2), but those either didn't do anything or limited the list to only one item, regardless of end value. Is there a way to limit appended children?