Is there a way to conceal the parent div when all of its child divs are hidden?

I have a series of dynamically created divs set up like this:

<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

To filter the results, I am utilizing the following script:

$(document).ready(function(){
  $("#search").on("keyup", function()
  {
    var value = $(this).val().toLowerCase();
    $(".child").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
  });
});

The current setup is functioning as expected. However, I would like to implement a feature where if the search value does not match any of the children in the first div, then the parent div (first div) should also be hidden.

Answer №1

Iterating through the parents and verifying if all children are currently not visible:

$('.parent').show();
$('.parent').each(function() {
  if (!$(this).find('.child:visible').length) {
    $(this).hide();
  } else {
    $(this).show();
  }
})

Answer №2

give this a shot

$(document).ready(function(){
    $("#search").on("keyup", function()
    {
      var value = $(this).val().toLowerCase();
      $(".child").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
      });
      //try out this code to hide
      $(".parent").each(function() {
        if($(this).find('.child:visible').length===0)
            $(this).hide();
        else 
            $(this).show();
        });
    });
  });

Answer №3

This scenario is akin to the one mentioned above, with the added benefit of being able to utilize the toggle_visibility() function in other locations as well.

function toggle_visibility() {
    if (!$(this).find('.child:visible').length) {
        $(this).hide();
    }
    else {
        $(this).show();
   }
}

$('.parent').each(toggle_visibility)

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

Ways to empty an angularJS array

let itemList = ['X', 'Y', 'Z']; Even though the array is cleared, the user interface does not reflect the change. itemList = []; This method solves the issue. But why? itemList.length = 0; ...

position the cursor at the end of the text within the text box

I am looking to move the cursor to the end of the text inside a text box that already contains text. Is there a way to achieve this using Java Script, CSS, or JQuery? <span> <input id="listInput" class="autocomplete-input singleselect-autocom ...

Navigating the terrain of multiple checkboxes in React and gathering all the checked boxes

I am currently developing a filter component that allows for the selection of multiple checkboxes. My goal is to toggle the state of the checkboxes, store the checked ones in an array, and remove any unchecked checkboxes from the array. Despite my attemp ...

Unbearably long wait for Ajax request

For some reason, my Javascript code is running incredibly slow, taking up to five minutes to complete. Sometimes after refreshing the page, certain requests haven't even been processed yet. I've already tried setting async:true, hoping it would ...

What is the proper way to install Vuetify when the webpack.config.js file is missing?

The Vuetify documentation mentions the following: After installation, you need to locate your webpack.config.js file and insert the provided code snippet into the rules array. If you already have a sass rule configured, you may need to make some adjustme ...

What is the best way to validate the accuracy of an HTML form response by using PHP through $.post, all while keeping the answer confidential?

Currently, I am working on a fill-in-the-blank quiz. In my PHP file named index.php, my objective is to validate the user's input against the correct answer stored in my MySQL server. One approach I considered was to simply echo the answer using < ...

Distribute the text evenly on either side of the center

I have a unique layout with two datalist elements centered, text positioned above, and two buttons integrated. body { background-color: DarkGray; } h1 { color: black; font-size: 30px; font-family: 'lucida console' } span { color: #4434 ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Having trouble with showing dynamic data in column2 of my HTML layout, and the alignment doesn't look quite right in HTML

I'm working with this HTML file, attempting to create a two-column layout using HTML and CSS. I want one column to be labeled REQUEST and the other RESPONSE. When a value is entered in the text field in Column 1, it should display a response in Column ...

Three.js analyzes the dominant color of an image rather than the image itself

I am experimenting with three.js and trying to apply an image as a texture to an object. However, I am only getting the dominant color of the image instead. I have searched online but couldn't find anyone facing similar issues. After inspecting the J ...

Getting the highest level object in a nested Angular component structure

Currently, I am in the process of developing a query builder using Angular that bears resemblance to the JQuery builder. However, I have encountered an issue related to emitting the data. Whenever I click on the addGroup or addRule buttons, a new group is ...

Prevent users from including spaces in their usernames during registration

I've encountered an issue with my registration form. It currently allows users to register usernames with spaces, such as "user name" instead of just "username" without any spaces. Despite searching and reading numerous tutorials, none have been of m ...

Error: The module "node_modules/react/index.js" does not export "default"

First time using Rollup to create a library and encountering an error with a basic button component when running rollup - c src/index.ts → dist/esm/index.js... [!] RollupError: "default" is not exported by "node_modules/react/index.js&qu ...

Removing white spaces from response HTML in JBoss 5.1 version

Does anyone know of a JBoss 5.1 plugin or utility that can automatically strip leading and trailing white spaces from HTML being sent as a response? Similarly, is there a way to do this for JSP files upon deployment? Any application-specific settings would ...

Combine the label and input within a single div tag

I'm attempting to enclose both my radio input and its respective label within a single div, but for some reason, it is not containing only the input. Here is my current code: The HTML code is as follows: <div class="payment_processor-section"> ...

The AngularJS Input Validation TypeError occurs when attempting to use an undefined function for validation

Currently, I am working on input validation using Angular. However, when the function is triggered, all elements return as undefined. The crucial code snippets are provided below, but do let me know if you need more information. Your assistance is greatly ...

I'd like to display just two names from a list at a time and have the option to click on a button to reveal the next two names, unfortunately, there

I am trying to modify my code so that it only displays the first 2 items in an array initially, and then on clicking a button, the next 2 names are displayed until the end. However, the code I have written seems to have a bug. Can you help me correct this ...

Leveraging HTML attributes in CMS source code

My website is built using Prestashop, and the content pages are created using: Prestashop > Preferences > CMS > Source-Code. For each CMS page, I utilize basic HTML in the source code. THE ISSUE I am attempting to add a widget to the site&apos ...

Although responseText functions properly, responseXML remains constantly null

I've searched through all available answers here and still can't find a solution. I'm confident that I haven't overlooked anything obvious. My issue involves loading map markers based on latitude and longitude coordinates. The problem ...

Signing out in React js

Hey everyone! I'm facing an issue. I have to create a logout form on React js that redirects to loginindex.html from hello.ejs and clears some variables using server.js, but I'm not sure how to do it =( Can anyone offer some guidance? Thank you! ...