Reputation: 6269
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'?
Upvotes: 0
Views: 312
Reputation: 11028
use fallowing code-
<script type="text/javascript">
alert($("div>div:contains('\\s*i\\s*$')").attr("id"));
</script>
Upvotes: 1
Reputation: 4035
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"));
Upvotes: 1
Reputation: 8318
This is one way:
<script type="text/javascript">
$("div").each(function() {
if ($(this).text() == 'i')
alert($(this).attr('id'));
})
</script>
Upvotes: 1
Reputation: 166031
$("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
.
Upvotes: 5