如何使用JavaScript编写一个搜索功能?
// Search function
function search(term) {
// Get all elements with the class name "search-result"
const results = document.querySelectorAll(".search-result");
// Filter the results based on the term
const filteredResults = results.filter(result => result.textContent.includes(term));
// Return the filtered results
return filteredResults;
}
// Example usage
const results = search("hello");
console.log(results);
Explanation:
-
search()
function:- Takes a string
term
as input. - Uses
document.querySelectorAll()
to find all elements with the class namesearch-result
. - Filters the results based on the
textContent
of each element. - Returns the filtered results as a list.
- Takes a string
-
exampleUsage
:- Calls the
search()
function with the term "hello". - Logs the results to the console.
- Calls the
How to use:
- Include the JavaScript code in your HTML document.
- Call the
search()
function with the desired term as an argument. - The function will return a list of elements that contain the term.
Example HTML:
Hello world
Another hello
How are you?
Output:
[Hello world]
Note:
- You can modify the
search()
function to filter based on different conditions. - You can also use this function to search for elements in specific elements on the page.