简体   繁体   English

给定 CSS 选择器的 Vanilla JavaScript 函数,用于查找 DOM 元素

[英]Vanilla JavaScript function to find DOM elements given a CSS selector

I need to write a function that takes a CSS Selector as a parameter and returns an array of DOM elements matching this selector.我需要编写一个函数,该函数将 CSS 选择器作为参数并返回与此选择器匹配的 DOM 元素数组。 I have to follow some rules.我必须遵守一些规则。

  • I cannot use any JS libraries.我不能使用任何 JS 库。
  • I cannot use querySelector/querySelectorAll.我不能使用 querySelector/querySelectorAll。

I have a variety of test CSS selectors that I need to test my function.我有多种测试 CSS 选择器需要测试我的功能。 I think I can pass the easy ones where they're either a single tag name, class name or ID name.我想我可以传递简单的那些,它们是单个标签名称、类名称或 ID 名称。 Then I can just do some if/else statements and call either document.getElementsByTag/Class/ID etc to get the elements.然后我可以做一些 if/else 语句并调用 document.getElementsByTag/Class/ID 等来获取元素。

function answer (selector) {
    if (selector.indexOf(".") >= 0)
        return document.getElementsByClassName(selector)
    else if (selector.indexOf("#") >= 0)
        return document.getElementById(selector)
    else 
        return document.getElementsByTagName(selector)
}

My problem is now if there are multiple selectors in a single query.我现在的问题是单个查询中是否有多个选择器。 Eg i am not sure how to handle the selector $div.a_class#an_id .例如,我不确定如何处理选择器$div.a_class#an_id My thinking was to split() the string at each .我的想法是 split() 每个 . or # and then chain search the document for each selector one by one, but it appears you can't do that.或 # 然后为每个选择器逐个链式搜索文档,但似乎您不能这样做。 Any help or guidance would be greatly appreciated.任何帮助或指导将不胜感激。

One option is to recursively search through the document's .children , and check whether the element being iterated element .matches the selector.一种选择是递归搜索文档的.children ,并检查被迭代的元素 element .matches是否与选择器.matches If it does, push it to an array:如果是,请将其推送到数组:

 const find = (selector, parent=document, arr=[]) => { [...parent.children].forEach((child) => { if (child.matches(selector)) { arr.push(child); } find(selector, child, arr); }); return arr; }; console.log(find('div.a_class#an_id'));
 <div> <div class="a_class" id="an_id">target!</div> </div>

function $(selector) {
  var element = [];
  for (let select of document.body.children) {
    if (select.matches(selector)) {
      element.push(select);
    }
  }
  return element;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM