I’m trying to create logic for my search bar to search through elements by their IDs, but it’s not working. As can be seen in the HTML code, the elements contain pictures. That’s why I’m using this method to display the elements.
here is the HTML code:
<html>
<html lang="en">
<head>
<title>BONIXS</title>
<link rel="shortcut icon" href="BONIXS.ico" type="image/x-icon">
<link rel="stylesheet" href="Ghost Runner.css">
</head>
<body>
<div>
<a href="D:/VSCODE/STEAM.html" id="Start">BONIXS</a>
</div>
<div>
<img src="Ghosrunner.png" alt="Ghost Runner" id="Ghostrunner">
</div>
<div class="Download">
<a href="Ghost Runner.zip" download>
<button class="Download-button">Download</button>
</a>
</div>
</body>
</html>
and here is the JavaScript logic code for it:
const searchBar = document.getElementById('searchBar');
const searchResults = document.getElementById('searchResults');
searchBar.addEventListener('keyup', function(event) {
console.log('Keyup event detected'); // Check if event listener is triggered
if (event.key === 'Enter') {
const searchTerm = searchBar.value.toLowerCase();
console.log('Search term:', searchTerm); // Check the search term
searchResults.innerHTML = '';
const matchingResults = performSearch(searchTerm);
console.log('Matching results:', matchingResults); // Check the matching results
displayResults(matchingResults);
}
});
function performSearch(searchTerm) {
const allElements = document.querySelectorAll('[id]');
return Array.from(allElements).filter(element => element.id.toLowerCase().includes(searchTerm));
}
function displayResults(results) {
results.forEach(result => {
const li = document.createElement('li');
li.textContent = result.id;
searchResults.appendChild(li);
});
}
I tried multiple times but it didn’t work
2
Answers
You can wrap the input in a form to get "Enter" functionality.
Note: Tyr typing "or" andpressing Enter
Your code is working as expected. There are no IDs elements in your HTML. Try to type for example "Ukraine" and you’ll see matching results.