Filter elements out of a jquery object based on text content

我怕爱的太早我们不能终老 提交于 2019-12-08 01:17:50

问题


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>

回答1:


Is this what you are looking for?

Fiddle

$(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):

Fiddle

$(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.




回答2:


Without filter as simple as

$("ul li:contains('two')").css('color', 'red');

WORKING DEMO




回答3:


$(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!