重构 DOM 搜索方法

Restructuring DOM searching method?

本文关键字:方法 搜索 DOM 重构      更新时间:2023-09-26

作为Chrome扩展程序的一部分,我正在整个DOM中搜索每个ID/Class中包含特定单词的元素。

目前它看起来像:

"allSelectors": document.querySelectorAll("[id*='example'][class*='example']"),
"collapse": function () {
                for (var i = 0; i < MyObject.allSelectors.length; i++) {
                    // Manipulate MyObject.allSelectors[i] etc
                }
}, 

首先,我想以某种方式重组它(可能使用 array ?),以便像这样轻松添加新的选择器:

 document.querySelectorAll("[id*='example'][class*='example'][id*='other'][class*='other']")

不容易扩展或好。

其次,我认为document.querySelectorAll非常慢 - 我使用它的原因是因为我需要搜索 id/class 中的任何地方(因此使用 *= ),并且不能使用大型外部库(例如 jQuery),因为这是一个小文件并且正在注入用户端。

这些问题有没有解决方案? 因为如果有很多比赛,那么这种缓慢可能会成为一个问题。

首先,

我完全会选择querySelectorAll,我认为它没有那么慢,而且它完全适合像你这样的情况。我同意你的观点,添加一个库是矫枉过正的,此外它可能不像有人想象的那么有益(让我们在这里测试一下)。

然后,我再次同意你的看法,即当前的解决方案不是很可扩展,阵列是要走的路。下面是使用数组的非常基本的实现:

// an array of classes and ids to match
var nodes,
    searches = [
  '[id*="test"]',
  '[class*="example"]'
];
// a simple function to return an array of nodes 
// that match the content of the array
function getNodes(arr){
  return Array.prototype.slice.call(document.querySelectorAll( arr.join() ));
}
nodes = getNodes(searches); 

好消息是可以轻松地在数组中添加或删除新的类和 id,例如,稍后您可以添加:

searches.push('[id*="some"]');
nodes = getNodes(searches); // new nodes will be fetched

这是一个带有完整示例代码的 jsbin。