我正在编写一个 UserScript,它将从包含特定字符串的页面中删除元素。
如果我正确理解 jQuery 的 contains() 函数,它似乎是完成这项工作的正确工具。
不幸的是,因为我将在其上运行 UserScript 的页面不使用 jQuery,所以我不能使用 :contains()。你们这些可爱的人中有人知道这样做的 native 方法是什么吗?
最佳答案
在现代浏览器中应该这样做:
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return [].filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}
然后像这样使用它:
contains('p', 'world'); // find "p" that contain "world"
contains('p', /^world/); // find "p" that start with "world"
contains('p', /world$/i); // find "p" that end with "world", case-insensitive
...
关于javascript - 相当于 jQuery :contains() selector 的 native javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17799236/