Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a 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");
        }
    });
});

The current method works well, but I'm wondering if there is a function that can directly test if an element contains certain text?

Currently, I am retrieving a list of all elements with the pattern and checking if the count is greater than zero. Is there a jQuery function that can efficiently determine if the pattern exists and return a boolean value? Since the table may have numerous rows, I aim to minimize unnecessary overhead.

Answer №1

///// substitute these lines...
// var val = $(this).find(":contains('" + filter + "')");
// if(val.length > 0){

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

This method involves converting the entire row content into a text string, followed by a basic string comparison operation to determine if the filter is present within the text (and consequently the row)

Answer №2

Discover a simpler method with the use of :contains

Here is a general approach:

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

For the specific example provided earlier, follow this format:

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

Learn more about it here: https://api.jquery.com/contains-selector/

This eliminates the need for using .each or .find.

Answer №3

To change a case-sensitive filter to be insensitive, follow these steps:

.match("/pattern/i"); 

Credit to Billy!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The response from the $.ajax call encounters an issue with the content-Type being set to application/json when the content is

Having a bit of trouble with the response content type. Here's the jQuery ajax request code I'm using: var settings = { dataType: 'json', url: 'services/loadTemplate.ashx', data: JSON.stringif ...

Automatically retrieve a URL from a website using Python

My approach to streamline my program and enhance user experience was by creating an executable file that consolidates all functions, including the download of various applications and their installation. However, I encountered a challenge where the link is ...

The Ineffectiveness of Social Media Sharing in WordPress

I'm encountering an issue with adding social media sharing buttons to my website's product page. Although I've implemented the PHP code, clicking on the Facebook button only redirects to a page displaying a share button and URL, but it doesn ...

Ways to retrieve the value of a concealed element without any activation signal

In my project, I've created a slider that dynamically shows different forms one by one. Each form contains a hidden element with a specific value that I need to retrieve (using its class) every time a new form is displayed. This way, I can use that el ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

I recently attempted a meyers reset and now I'm struggling to get my unordered list to display in a horizontal layout

Check out my code snippet below: .navbar-container { width:100%; display:inline-block; } ul { list-style-type: none; display: inline; } <div class="navbar-container"> <ul> <li><a href="gmail.com">Gmail</a>& ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

How can I remove the unsightly scrollbar caused by overflow: auto?

I've encountered a problem while working on my website. The inner div #content wasn't expanding to the full size of the page, causing the text to overflow messily over the background image and making it difficult to read. I initially used overflo ...

Internet Explorer displaying incorrect shadow effects (paper curl) with CSS

I am attempting to achieve a page curl effect similar to this one: https://i.stack.imgur.com/grS7p.png I have followed the example provided here: http://codepen.io/anon/pen/fpjoa When I create new PHP and CSS files and copy-paste the code from the afore ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Persistent footer overlaps lower body content

Issue with Sticky Footer in Safari I recently added a sticky footer to my website, but I'm facing problems with it covering the body content on Safari. It works fine on Chrome and Firefox after adding a bottom margin to the body to adjust for the hei ...

Using JQuery, remove any duplicate items from one list box and populate another list box

I have two list boxes set up: the leftBox contains all available options, while the rightBox displays the selected options. I am already familiar with how to add and remove items from each list box using jquery. However, my current goal is to automatically ...

The code for the bouncing image isn't functioning properly outside of the JSFiddle environment

I'm having issues with this jQuery snippet in my web application. It works fine on jsfiddle, but not when I add it to my project. Here's the code: $('.myimage').mouseenter(function() { $(this).effect('bounce',500); }); Her ...

Creating image links in this jQuery Slider plugin: A beginner's guide

Currently, I am attempting to insert links into each photo within the slider. While I have successfully done this on two other websites, I am encountering difficulties due to variations in the code structure. <a href="http://www.google.com I have expe ...

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

Creating an addition button using jQuery on-the-fly

Looking to implement pagination using jQuery and Ajax. The first hurdle I've come across is figuring out how to add a button dynamically. <div class="btn-group" id="pagination_group"> <button class="btn" disabled="disabled">First</ ...

Unable to access placeholder information from the controller

I am new to implementing the mean stack. I attempted to view data from the controller, but encountered an error message in the web browser's console. Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.3/$controller/ctrlreg?p0=AppCtrl Stack ...

What is the process for updating a particular div element?

I am currently developing a webpage that allows users to select an item, and the relevant information will be displayed. On this page, I have incorporated two buttons: btnBuy0 and btnBuy1. The functionality I am aiming for is that when BtnBuy0 is clicked ...

Tips for fetching individual item information from Firebase real-time database using Angular 9 and displaying it in an HTML format

product.component.ts import { AngularFireDatabase } from '@angular/fire/database'; import { ProductService } from './../product.service'; import { ActivatedRoute } from '@angular/router'; import { Component, OnInit} from &apo ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...