Native javascript equivalent of jQuery :contains() selector

coulbourne picture coulbourne · Jul 23, 2013 · Viewed 13.6k times · Source

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

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

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

Answer

elclanrs picture elclanrs · Jul 23, 2013

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);
  });
}

Then use it like so:

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
...