teacher
teacher

Reputation: 1015

How to search a text in jquery?

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...

Upvotes: 0

Views: 2843

Answers (6)

Amjad Masad
Amjad Masad

Reputation: 4035

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

Upvotes: 1

karim79
karim79

Reputation: 342635

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.

Upvotes: 1

user657496
user657496

Reputation:

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();
});

Upvotes: 1

genesis
genesis

Reputation: 50976

$("p").each(function(a,b){
   if ($(this).html() == 'i'){
      console.log(a);
   }
});

or

$("p").filter(function(){
   return $(this).html() == 'i';
});

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219930

$('p').filter(function() {
    return $(this).text() === 'i';
});

Upvotes: 4

Emil Ivanov
Emil Ivanov

Reputation: 37633

Use $.filter.

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

$('div').filter(function () {
    return $(this).html() == 'i';
});

Upvotes: 5

Related Questions