如何使用JavaScript编写一个搜索功能?

如何使用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:

  1. search() function:

    • Takes a string term as input.
    • Uses document.querySelectorAll() to find all elements with the class name search-result.
    • Filters the results based on the textContent of each element.
    • Returns the filtered results as a list.
  2. exampleUsage:

    • Calls the search() function with the term "hello".
    • Logs the results to the console.

How to use:

  1. Include the JavaScript code in your HTML document.
  2. Call the search() function with the desired term as an argument.
  3. 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.
相似内容
更多>