I am trying to use contains
with 'this' keyword, but it is giving an error.
JS
$(function(){
var check=$('ul').find('li').filter(function(){
return $(this:contains('two')).css('color','red')
})
})
HTML
<ul>
<li id="one">one</li>
<li id="two">two</li>
<li id="one">one</li>
<li id="two">two</li>
<li id="one">one</li>
<li id="two">two</li>
<li id="one">one</li>
<li id="two">two</li>
<li id="one">one</li>
<li id="two">two</li>
</ul>
Is this what you are looking for?
$(function () {
$('ul').find('li').filter(function () {
return this.innerHTML == 'two';
}).css('color','red')
})
Or to match it anywhere in the element (rather than only "two" being within it):
$(function () {
$('ul').find('li').filter(function () {
return /two/.test(this.innerHTML);
}).css('color','red')
})
Also, if it matters... chaining methods (.find().filter()
) seems to be faster than using contains
:
Performance test created for this specifically
Another related test
And your id's should be unique - but I'm assuming that it is just copy/pasting for sample code and that you don't actually have duplicate id's in your actual code.
$(this).text() == 'two';
Get the current li's text & check if it has the value "two".
来源:https://stackoverflow.com/questions/18317082/filter-elements-out-of-a-jquery-object-based-on-text-content