我正在编写一个用户脚本,该脚本提取与指定CSS选择器匹配的所有链接,然后在这些链接的子节点之间执行几次搜索,然后更改找到的元素的属性。我正在寻找一种方法,使搜索前每次都不会使所有匹配第一个选择器的链接都匹配,而只能一次。HTML示例:
<div>
<a class="some_class" href="http://some_href"><b>Link1</b></a>
<a class="another_class" href="http://another_href"><b>Link2</b></a>
<a class="some_class" href="http://www.some_href">Link3</a>
</div>
<span>
<a class="some_class" href="some_href"><b>Link4</b></a>
</span>
Javascript:
var links=document.querySelectorAll('a.some_class');
//some actions with the hrefs
//the following code could be a solution, but doesn't work as I need.
//it tries to get b elements from the extracted links with matching href
//but generally this selector depends on some calculations with links
links.querySelectorAll('a[href$="some_href"] b')[0].style.display='none';
//NodeLists don't have this method
//another way:
//trying to create document fragment from NodeList to call method on it
var fragment=document.createDocumentFragment();
for(var i=0; i<links.length; i++){
fragment.appendChild(links[i]);
//Link is removed from page, so this also is not suitable
}
当然,我可以简单地遍历NodeList的所有子项,但是如果有很多链接和很多搜索,那太慢了。
您正在谈论的是对列表进行过滤。
所以首先您得到列表:
var links=document.querySelectorAll('a.some_class');
然后,您想对其进行过滤,例如仅查找那些也匹配的对象a[href$="some_href"] b
(但我知道,具体取决于所讨论的链接而有所不同)。
我可能首先将NodeList设置为数组:
links = Array.prototype.slice.call(links, 0);
...所以我可以在上面使用各种漂亮的Array方法。
然后:
var bElementsUnderSomeHref = [];
var someOtherCriterion = [];
links.forEach(function(link) {
var b;
if (link.href.substr(-9) === "some_href") {
b = link.querySelector("b");
if (b) {
bElementsUnderSomeHref.push(b);
}
}
if (/*...some other criterion...*/) {
someOtherCriterion.push(/*...something relevant...*/);
}
});
在那里,我正在做一个单圈,但如果您有任何理由需要,您可以使用单独的循环。一个循环可以为您节省一些执行时间,但这并不是很慢。正如我上次演示的那样,您甚至想问这个问题,即使IE8都可以循环(说)20,000个元素,并在很短的时间内对每个元素进行嵌套querySelector
/querySelectorAll
调用。对我而言,旧XP VM中的IE8只需320毫秒即可完成。Chrome可以在60岁以下完成它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句