You can use $.grep()
to return an array of matches, or .filter()
to return a jQuery collection of elements, where the return value of the callback should be Boolean
true
or false
$.grep()
$(function() {
var text = "abc";
var res = $.grep($("li"), function(el, index) {
return el.textContent === text
});
// `res` is an array containing one or more `DOM` elements
console.log(res);
res[0].style.color = "red";
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul>
<li>abc</li>
<li>def</li>
<li>ghi</li>
</ul>
.filter()
$(function() {
var text = "def";
var res = $("li").filter(function(index, el) {
return el.textContent === text
});
// `res` is a jQuery object containing one or more `DOM` elements
// where jQuery methods can be chained
console.log(res);
res.css("color", "green");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul>
<li>abc</li>
<li>def</li>
<li>ghi</li>
</ul>
If you are trying to determine if a given element has .textContent
, and if true
do stuff, you can use .is()
, which returns a Boolean
; either true
or false
$(function() {
var text = "ghi";
var i = 0;
var res = $("li").is(function(index, el) {
i = index;
return el.textContent === text
});
// `res` is a `Boolean`
console.log(res);
if (res) {
alert(text + " has already been set");
$("li").eq(i).css("color", "gold");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul>
<li>abc</li>
<li>def</li>
<li>ghi</li>
</ul>