Conceal the main container when the subsequent inner div has no content

I have a setup that looks something like this:

<div class="parent">
   <div class="child1">Header</div>
   <div class="child2">
      <div class="grandchild"></div>
      <div class="grandchild"></div>
      <div class="grandchild"></div>
   </div>
</div>

My goal is to hide the parent div when .child2 contains no elements. I've attempted this solution, but it doesn't seem to be working:

$(".child2:empty").parent().hide();

Could you point out what might be going wrong? Feel free to check out my sample fiddle.

UPDATE:
I should clarify that instead of .child2 being empty, I actually want the children divs of .child2 to have a display:none property. You can see the revised version of my fiddle here

Answer №1

Give this a try and see the magic,

$(document).ready(function() {
    var secondChildDiv = $(".child2");

    if (secondChildDiv.html() == "") {
        secondChildDiv.parents().hide();
    }

});

Answer №2

The issue with your current code is the presence of whitespace between <div class="child2"> and </div>. By removing this whitespace, your code should work as intended:

$(".child2:empty").parent().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child1">Parent 1</div>
   <div class="child2">
      <div class="grandchild">GC1</div>
      <div class="grandchild">GC2</div>
      <div class="grandchild">GC3</div>
   </div>
</div>

<div class="parent">
   <div class="child1">Parent 2</div>
   <div class="child2"></div>
</div>

If you are unable to modify the HTML to remove the whitespace, an alternative solution is to use filter() and children():

$(".child2").filter(function() {
    return $(this).children().length == 0;
}).parent().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child1">Parent 1</div>
   <div class="child2">
      <div class="grandchild">GC1</div>
      <div class="grandchild">GC2</div>
      <div class="grandchild">GC3</div>
   </div>
</div>

<div class="parent">
   <div class="child1">Parent 2</div>
   <div class="child2">
   </div>
</div>

Answer №3

give this a shot

$.each($(".child2"),function(){
   if($(this).children().length==0)
   {
     $(this).parent().hide();
   }
});

Answer №4

It is recommended to trim HTML content before processing it:

$(".child2").filter(function() {
    return !$(this).html().trim();
}).parent().hide();

The issue seems to be related to the presence of whitespaces within your DIV. In CSS4, you can address this using the :blank pseudo-class.

UPDATE: If you want to ensure that the div only contains hidden children (or no displayed content), you could verify its scrolling height:

$(".child2").filter(function() {
  return !this.scrollHeight;
}).parent().hide();

Alternatively, a more reliable approach would be:

$(".child2").filter(function() {
  return $(this).children().length === $(this).children().filter(':hidden').length;
}).parent().hide();

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

What could be causing my border to not function properly?

When examining the page, I noticed that the borders overlap and thicken due to the detail section. I tried to eliminate all borders of the details class using CSS, but unfortunately, it didn't work as expected. The bottom border stubbornly remains in ...

What steps should be followed to display an HTML page within an HTML div?

The question I have is a bit misleading, as I'm not looking for guidance on how to open an HTML document in a div. Rather, I am currently facing an issue where I am unable to replace the HTML file that I have already placed in a div. Initially, I pla ...

Redesigned the .filter function in my code

$(document).ready(function() { var $a = $('.post td span a'); $a.filter(function() { return $(this).css('color') === "#0000ff"; }).closest('td').removeClass('row1 row2').next('td').removeClass('row ...

Attempting to arrange all the images in a horizontal display rather than a vertical one

This is my first ever question on the forum sorry if it is unprofessional hopefully i can learn from my mistakes on this post!! I put the question in the title but if you have any questions feel free to ask below THANK YOU! for the help! My Code ...

Use jQuery's animate function to toggle a different div when clicking on one

Having trouble with a jQuery function that keeps triggering the second function every time I click. How can I fix this issue? I designed a navbar with 3 links, each linked to a different .contentDiv with unique IDs. Whenever a link is clicked, a toggle fu ...

Updating Content Dynamically with AJAX, JavaScript, and PHP without requiring a page reload or user action

Currently, I'm delving into the world of JS/AJAX functions that operate without the need for a page refresh or button click. However, I've encountered an issue when trying to echo the value. Oddly enough, when I change this line $email = $_POST ...

Change the HTML data received from an AJAX post response using jQuery

Attempting to change html data from an ajax post response. var check = '<option value="">All</option>'; var urlpage = 'select.php'; $("select#s1").change(function(){ var s1 = $("select#s1 option:selected").prop("value"); ...

Custom hover title to transform table into grid

I'm currently working on creating an HTML table and integrating it with the following code: tableToGrid('#grid', {cmTemplate: {sortable:false}}); The original structure of my HTML table is as follows: <tr><th>Month</th>& ...

Programming the action of unfolding one window while simultaneously closing all others

I am facing an issue where the foldout function is working perfectly, but I need the second function to run first in order to close all other elements. Unfortunately, I can't seem to figure out what the problem is. Any help would be greatly appreciate ...

The XMLHttpRequest is unable to load.... The origin null has been restricted by Access-Control-Allow-Origin

I'm having trouble printing a JSON from a broker on my server. I am unable to return the JSON as Chrome gives me the following error: XMLHttpRequest can not load .... Origin null is not allowed by Access-Control-Allow-Origin. Can anyone help me wi ...

Responsive Navigation Bar with Bootstrap

Struggling with the Bootstrap 4 navbar issue, specifically trying to close it when the <a> within the <li> tag is clicked. Experimented with data-toggle="collapse" data-target=".navbar-collapse.show" inside the <a> tag and it worked, but ...

Learn how to extract an entire table from a website using Kimono Labs, rather than just the first ten rows

Currently, I am utilizing Kimono labs to generate an API for scraping data from the table on this specific website. However, the website only displays the initial 10 rows of the table by default, limiting my API output to just 10 rows. Is there a method to ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

Converting HTML entities to actual characters in Angular2: How to change apostrophe's code to apostrophe symbol

This is the text I have stored in my database: https://i.sstatic.net/vr3op.png When this text is accessed in an angular2 application and rendered, it displays HTML numbers. For example, a single quote(') appears as "HTML Number '" If you need ...

Preventing a JavaScript function from executing multiple times

Having only recently started learning javascript and jquery, I encountered a problem where one of my functions kept executing itself when calling another function. Despite trying various solutions found here, the function either stopped executing altogethe ...

Show a row of pictures with overflow capabilities

I am looking to develop my own image viewer that surpasses the capabilities of Windows. My goal is to design an HTML page featuring all my images laid out horizontally to maximize screen space. I also want the images to adjust in size and alignment as I z ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Troubleshooting Problem with Website Responsiveness on iPhones Using Bootstrap 5

I am currently experiencing a challenge involving the responsiveness of a website I am developing, particularly when it comes to iPhones. The site utilizes Bootstrap 5 and displays correctly on Android devices and in Chrome Dev Tools. However, upon testing ...

Ensure that the top border is aligned perfectly with the top of the page while keeping the text in its

I am a beginner student working on my very first project, so I appreciate your patience as I learn. Currently, I am trying to add a hover effect to the navigation bar links where a blue bar appears at the top of the link and touches the border of the page ...