I have to filter a html-table. To do so I created an each callback for all tr
elements and test if one of the tr-children
contain some specific pattern.
$("#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");
}
});
});
It works, but is there an function to test if a element contains some text?
At the moment I retrieve a list of all elements containing the pattern and count if it's bigger than zero. Is there a jQuery function, which tests if this pattern occurs and returns a boolean? The table can contain many rows and therefore I want as little overhead as possible.
To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
///// replace these lines...
// var val = $(this).find(":contains('" + filter + "')");
// if(val.length > 0){
///// with this line
if($(this).text().match(filter)){
This works by converting the whole row content into a text string, then using simple string comparison function to check if filter is contained inside the text (and therefore the row)
The answers are good, but there's an easier way using :contains
In general, do this:
$(".class:contains('texttofind')").css("display", "none");
With the specific example above, do this:
$("#table1 tr[data-config]:contains('" + filter + "')").css("display","table-row");
You can find out more here: https://api.jquery.com/contains-selector/
This avoids having to loop with .each
or .find
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With