Check if children contain specific text using jQuery

I need to filter the html table. To do this, I created each callback for all the elements trand checked if one of the contains a tr-childrenspecific template.

$("#filter").keypress(function() {
    var filter = $(this).val();

    $("#table1 tr[data-config]").each(function(){

        var val = $(this).find(":contains('" + filter + "')");

        if(val.length > 0){
            $(this).css("display","table-row");
        }else{
            $(this).css("display","none");
        }
    });
});

This works, but is there a function to check if the element contains any text?

At the moment, I get a list of all the elements containing the template, and count if it is greater than zero. Is there a jQuery function that checks if this pattern happens and returns a boolean? A table can contain many rows, and therefore I want as little overhead as possible.

+5
source share
3 answers
///// replace these lines...
// var val = $(this).find(":contains('" + filter + "')");
// if(val.length > 0){

///// with this line
if($(this).text().match(filter)){

, , , , (, , )

+4

, :

.match("/pattern/i"); 

Billy!

0

The answers are good, but there is an easier way to use: contains

In general, do the following:

$(".class:contains('texttofind')").css("display", "none");

In the above example, do the following:

$("#table1 tr[data-config]:contains('" + filter + "')").css("display","table-row");

You can find out more here: https://api.jquery.com/contains-selector/

This avoids the loop with .eachor .find.

0
source

All Articles