admin管理员组

文章数量:1297119

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

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

Share Improve this question asked Aug 16, 2011 at 12:12 teacherteacher 1,0153 gold badges15 silver badges28 bronze badges 2
  • Do you want to for the full content of elements, or for words? – Felix Kling Commented Aug 16, 2011 at 12:16
  • 2 Exact duplicate: stackoverflow./questions/7076159/… – Patrick Commented Aug 16, 2011 at 12:16
Add a ment  | 

6 Answers 6

Reset to default 5

Use $.filter.

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

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

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

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

or

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

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

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.

本文标签: javascriptHow to search a text in jqueryStack Overflow