33

As said in the title, I'd like to find something like :contains() but to match an exact string. In other words, it shouldn't be a partial match. For example in this case:

<div id="id">
   <p>John</p>
   <p>Johny</p>
</div>

$("#id:contains('John')") will match both John and Johny, while I'd like to match only John.

Thanks in advance.

EDIT: ES2015 one-liner solution, in case anyone looked for it:

const nodes = [...document.querySelectorAll('#id > *')].filter(node => node.textContent === 'John');

console.log(nodes);
/* Output console formatting */
.as-console-wrapper { top: 0; }
.as-console { height: 100%; }
<div id="id">
  <p>John</p>
  <p>Johny</p>
</div>
Przemek
  • 3,855
  • 2
  • 25
  • 33

4 Answers4

41

You can use filter for this:

$('#id').find('*').filter(function() {
    return $(this).text() === 'John';
});

Edit: Just as a performance note, if you happen to know more about the nature of what you're searching (e.g., that the nodes are immediate children of #id), it would be more efficient to use something like .children() instead of .find('*').


Here's a jsfiddle of it, if you want to see it in action: http://jsfiddle.net/Akuyq/

jmar777
  • 38,796
  • 11
  • 66
  • 64
11

jmar777's answer helped me through this issue, but in order to avoid searching everything I started with the :contains selector and filtered its results

var $results = $('#id p:contains("John")').filter(function() {
    return $(this).text() === 'John';
});

Heres an updated fiddle http://jsfiddle.net/Akuyq/34/

PaulParton
  • 1,013
  • 1
  • 11
  • 19
  • 5
    Just noticed this answer was posted here. Just in case anyone else comes across this, it's actually *less* efficient to add the `:contains()` check. Internally, `:contains()` has to loop over all the elements and perform a regex comparison for `"John"`. We then have to loop over everything that passed that check with `filter()` on top of that. Basically, worst-case complexity for this version is `O(2n)`, whereas every-case for mine is just `O(n)` (and yeah, I realize that sort of abuses Big O Notation, there...). – jmar777 Oct 14 '14 at 20:03
0

Simple way is "select element by exact match" using pseudo function.

Solution Select element by exact match of its content

Mehmet Hanoğlu
  • 2,942
  • 1
  • 13
  • 19
0

You could try writing a Regular Expression and searching off of that: Regular expression field validation in jQuery

Community
  • 1
  • 1
Steve Sloka
  • 3,444
  • 2
  • 22
  • 29
  • It doesn't works really fine for me. Except that I also need to find solution how to search for string `John` between childrens of `#id`. – Przemek Sep 27 '11 at 14:55