Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native javascript equivalent of jQuery :contains() selector

Tags:

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

like image 634
coulbourne Avatar asked Jul 22 '13 23:07

coulbourne


People also ask

Is jQuery native JavaScript?

Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.

How use contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

Is jQuery a selector?

The is( selector ) method checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. If no element fits, or the selector is not valid, then the response will be 'false'.

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.


1 Answers

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 ... 
like image 67
elclanrs Avatar answered Oct 23 '22 17:10

elclanrs