List of only the elements that contains

Neeraj Singh

Neeraj Singh

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]

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.