Filter elements out of a jquery object based on text content

…衆ロ難τιáo~ 提交于 2019-12-06 14:01:10

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.

Without filter as simple as

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

WORKING DEMO

$(this).text() == 'two';

Get the current li's text & check if it has the value "two".

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