推荐答案
function find(selector) {
return document.querySelectorAll(selector);
}本题详细解读
1. 函数功能
find(selector) 函数的作用是根据传入的选择器 selector 查找并返回匹配的 DOM 元素。该函数使用了 document.querySelectorAll 方法来实现选择器的匹配。
2. 代码解析
document.querySelectorAll(selector):这是 JavaScript 提供的原生方法,用于返回文档中与指定选择器匹配的所有元素。它返回的是一个NodeList对象,类似于数组,但并不是真正的数组。selector:这是一个字符串参数,表示要查找的 CSS 选择器。例如,".class-name"、"#id-name"、"div"等。
3. 使用示例
// 查找所有 class 为 "example" 的元素
const elements = find(".example");
// 查找所有 <div> 元素
const divElements = find("div");
// 查找 id 为 "main" 的元素
const mainElement = find("#main");4. 注意事项
document.querySelectorAll返回的是一个NodeList,虽然它类似于数组,但它没有数组的所有方法(如map、filter等)。如果需要使用数组方法,可以将其转换为数组:const elementsArray = Array.from(find(".example"));- 如果选择器匹配不到任何元素,
document.querySelectorAll会返回一个空的NodeList,而不是null或undefined。