0

i have a question that if i want to search a perticular text in any page using jquery. what i don't want is that

<p id="1">iii</p>
<p id="2">i</p>
<p id="3">ibiib</p>
<p id="4">bb</p>
<p id="5">tina</p>

 <script type="text/javascript">
    console.log($("div:contains('i')"));
 </script>

this above code gives me all paragraphs except id=4; but what i want is only paragraph with id=2 to be selected. if there is a way to do that in javascript or any other library reply me...

teacher
  • 1,005
  • 3
  • 15
  • 27
  • Do you want to for the full content of elements, or for words? – Felix Kling Aug 16 '11 at 12:16
  • 2
    Exact duplicate: http://stackoverflow.com/questions/7076159/how-can-i-get-an-element-containing-exactly-the-specified-text-using-jquery/7076346#7076346 – Patrick Aug 16 '11 at 12:16

6 Answers6

5

Use $.filter.

This will return the divs, which contains just one i.

$('div').filter(function () {
    return $(this).html() == 'i';
});
Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
4
$('p').filter(function() {
    return $(this).text() === 'i';
});
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • @frndsforever: If an answer has solved your problem, click on the check mark next to it to accept it, so that others coming to this post will know that it is the correct answer. – Joseph Silber Aug 16 '11 at 12:26
1
$("p").each(function(a,b){
   if ($(this).html() == 'i'){
      console.log(a);
   }
});

or

$("p").filter(function(){
   return $(this).html() == 'i';
});
genesis
  • 50,477
  • 20
  • 96
  • 125
1

You can loop through the paragraphs and check if their content is the same as your desired content. I used a jQuery loop, you can use javascript if you want. JSFIDDLE

$('p').each(function() {
    if(this.innerHTML == 'i') doWhateverYouWant();
});
1

I would use a simple plugin for this:

$.fn.exactMatch = function(str) {
    return this.filter(function() {
        return $(this).text() === str;
    });
};

$("p").exactMatch("i").css("border", "1px solid red");

You can try it here.

karim79
  • 339,989
  • 67
  • 413
  • 406
1

You can extend jQuery's selector engine to add a new one:

$.expr[':'].texteq = function( elem, i, match, array ) {
    return $(elem).text() === match[3];
};

console.log($('p:texteq(i)'));

Example

Amjad Masad
  • 4,035
  • 1
  • 21
  • 20