How can I check f a keyword exists in a div?
for instance, this is my html,
<div class="item">
<div class="title">How to check if a keyword exists</div>
<div class="author">John J, 1990</div>
</div>
I tried with this method below but obviously doesn't work!
if ($('.item .author').text('John J').length > 0)
{
alert('开发者_运维知识库found John J');
}
any ideas? thanks.
You can use the :contains
selector, like this:
if ($('.item .author:contains("John J")').length > 0)
{
alert('found John J');
}
...or what you're probably ultimately after, something like this:
$('.item .author:contains("John J")').addClass("highlight");
By calling .text()
you're setting the text, not checking for it. Using .text()
for searching would look like this:
if ($('.item .author').text().indexOf("John J") != -1)
{
alert('found John J');
}
if ($('.item .author')[0].innerText.indexOf('John J')!=-1)
{
alert('found John J');
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="item">
<div class="title">How to check if a keyword exists</div>
<div class="author">John J, 1990</div>
</div>
I tried with this method below and it now works!
精彩评论