0

I have a list each containing a text value. How do I get the list object having exactly a given text value?

<div id="child4"></div>

<div id="child5">ib</div>

<div id="child6"></div>

<div id="child7">ii</div>

<div id="child8">iii</div>
<div id="child1" width="200px"></div><div id="child2">i</div>

 <script type="text/javascript">
    alert($("div>div:contains('i')").attr("id"));
 </script>

The above script gives me all the div that contains the text value i..How can I fix this so that i get an element having exactly the same text value as 'i'?

Vivek
  • 10,978
  • 14
  • 48
  • 66
Manish Basdeo
  • 6,139
  • 22
  • 68
  • 102

4 Answers4

5
$("div > div").filter(function() {
   return $(this).text() === "i"; 
});

The filter method returns only elements that match the condition. The condition will only match elements whose text is the specified string.

Note that in your example, this will not match anything, as your selector div > div will select div elements that are direct children of another div, and the elements in your example have no parent div.

Here's an example of the code running. In the example, I've changed the selector to just div.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • It's the strict equality operator. It prevents JavaScript converting between types. In this case, it makes no difference, you could just as easily use `==`, but it's good practice to use it when you don't want type coercion to occur. For more info, see this question: http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – James Allardice Aug 16 '11 at 10:36
1

use fallowing code-

<script type="text/javascript">
    alert($("div>div:contains('\\s*i\\s*$')").attr("id"));
 </script>
Vivek
  • 10,978
  • 14
  • 48
  • 66
1

This is one way:

 <script type="text/javascript">
     $("div").each(function() {
         if ($(this).text() == 'i')
             alert($(this).attr('id')); 
        })
 </script>
Patrick
  • 8,175
  • 7
  • 56
  • 72
1

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

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

alert($("div:texteq('i')").attr("id"));

Example

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