List of only the elements that contains

Neeraj Singh

By Neeraj Singh

on April 12, 2010

I was toying with simple list filter plugin and ended up with this markup.

1<div id="lab">
2  <ul id="list">
3    <li><a href="">USA</a></li>
4  <ul>
5  <p>
6    <a href=''>USA</a>
7  </p>
8</div>

I want to get all links that contains the word USA. Simple enough. jQuery supports contains selector.

1$(":contains('USA')");

Above query results in following items.

1[html, body#body, div#lab, ul#list, li, a, ul, p, a]

That is because contains looks for given string under all the descendants.

has method to rescue

jQuery has method which returns the list of elements which have a descendant which has the given string.

1b = $("*").has(":contains('USA')");

Above query results in following items.

1[html, body#body, div#lab, ul#list, li, ul, p]

Final result

1a = $(":contains('USA')");
2b = $("*").has(":contains('USA')");
3c = a.not(b);
4console.log(c);

Above query results in following items.

1 [a, a]

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.