本机javascript相当于jQuery:contains()选择器 [英] Native javascript equivalent of jQuery :contains() selector

查看:149
本文介绍了本机javascript相当于jQuery:contains()选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个UserScript,它将从包含某个字符串的页面中删除元素。

I am writing a UserScript that will remove elements from a page that contain a certain string.

如果我正确理解了jQuery的contains()函数,它似乎是正确的工作工具。

If I understand jQuery's contains() function correctly, it seems like the correct tool for the job.

不幸的是,由于我将运行UserScript的页面不使用jQuery,我不能使用:contains()。你们中的任何一个人都知道这样做的原生方式是什么?

Unfortunately, since the page I'll be running the UserScript on does not use jQuery, I can't use :contains(). Any of you lovely people know what the native way to do this is?

http://codepen.io/coulbourne/pen/olerh

推荐答案

这应该在现代浏览器中实现:

This should do in modern browsers:

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()选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆