Ways to dynamically conceal an HTML element when another element is devoid of content

How can I dynamically hide the heading above a div if that div is empty? The content of the div will change based on user input. I would like the heading1 to appear immediately after a button click event.

I am inclined towards a CSS solution, although the page already utilizes jQuery and JavaScript extensively, so I am open to all suggestions.

If assigning unique IDs to all headings simplifies the task, I am willing to go down that route as well.

function addcontent()
{
document.getElementById("Content1").innerHTML = "Extra Content";
}

$(".rulescontent:empty").parent().hide();
$(!".rulescontent:empty").parent().show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h1>heading1</h1>
  <div style="font-size:90%" id="Content1" class="rulescontent"></div>
</div>

<div>
  <h1>heading2</h1>
  <div style="font-size:90%" id="Content2" class="rulescontent"></div>
</div>
    
<button  type='button' onclick="addcontent()">add content</button>

Other Stackoverflow solutions do not handle scenarios where the content reappears once it is no longer empty.

Answer №1

To ensure that your div displays the added content correctly, it is important to create a function and invoke it whenever you append new content.

function addNewContent() {
  document.getElementById("Content1").innerHTML = "Additional Content";
  toggleEmptyItems()
}

function toggleEmptyItems() {
  $(".rulescontent:empty").parent().hide();
  $(".rulescontent:not(:empty)").parent().show();
}
toggleEmptyItems()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h1>Title 1</h1>
  <div style="font-size:90%" id="Content1" class="rulescontent"></div>
</div>

<div>
  <h1>Title 2</h1>
  <div style="font-size:90%" id="Content2" class="rulescontent"></div>
</div>

<button type='button' onclick="addNewContent()">Add New Content</button>

Answer №2

To streamline the process of updating the content in your rulescontent divs without manually adding code to each instance, consider utilizing a MutationObserver. Here's an example implementation:

function addcontent(id) {
   document.getElementById(id).innerHTML = "Extra Content";
}
function removecontent(id) {
   document.getElementById(id).innerHTML = "";
}

$(".rulescontent:empty").parent().hide();
$(!".rulescontent:empty").parent().show();

// Define options for the observer
let config = { childList: true };

// Callback function to handle observed mutations
let callback = function(mutationsList, observer) {
    for (let mutation of mutationsList) {
        $(mutation.target.parentNode)
          .toggle(! $(mutation.target).is(':empty'));
    }
};

$('.rulescontent').each(function() {
    // Create an observer instance linked to the callback function
    let observer = new MutationObserver(callback);

    // Start observing the target node for specified mutations
    observer.observe(this, config);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Test Case</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div>
  <h1>heading1</h1>
  <div style="font-size:90%" id="Content1" class="rulescontent"></div>
</div>

<div>
  <h1>heading2</h1>
  <div style="font-size:90%" id="Content2" class="rulescontent"></div>
</div>
    
Section 1: <button  type='button' onclick="addcontent('Content1')">add content</button>
<button  type='button' onclick="removecontent('Content1')">remove content</button>
<br>
Section 2: <button  type='button' onclick="addcontent('Content2')">add content</button>
<button  type='button' onclick="removecontent('Content2')">remove content</button>
</body>
</html>

(Inspired by the MutationObserver MDN example.)

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

Utilize multiple background images in CSS with a set of three unique images

I have inserted three images into the background of my website's body. Two of them are displaying correctly (one with repeat-y), but the third one is not working. I've tried searching a lot but couldn't find a solution. body { backgr ...

Can you explain the distinction between max-width and min-width in media queries for HTML and CSS?

Could you explain the distinction between max-width and min-width in media queries in HTML and CSS? @media (min-width:480px) { /* styles for smartphones, Android phones, and landscape iPhone */ } @media (min-width:600px) { /* styles for portrait tabl ...

Issue with Bootstrap cards overlapping while searching

On my Bootstrap 4 page, I've incorporated cards that can be searched, displaying only those with matching titles. However, I am facing two main issues. Firstly, when two matching cards are on the same row, they overlap. Secondly, if a matching card is ...

Accessing the current instance in Vue when triggered by a checkbox event

Recently, I tested out a to-do-list application built in Vue that has a checkbox feature to mark completed items. I'm looking for a way to access the current instance from the checkbox event. Here's what I've accomplished so far: myObject ...

Establishing MQTT Connection in Ionic 3

I am facing a challenge with implementing Publish-Subscribe methods in my Ionic 3 application. After consulting the information on this page, I attempted to link MQTT with my Ionic 3 application. Can anyone guide me on how to successfully connect MQTT wi ...

Dealing with 404 page not found error without replacing the default in Next.js 13

I followed the Next.js 13 documentation's suggestion to create a file called not-found.jsx in my app directory to handle 404 errors. But, despite placing it inside the app directory and intended for layout and loading purposes, it is not overriding th ...

cross-domain ajax response

Imagine a unique scenario that will pique the interest of many developers. You have a JavaScript file and a PHP file - in the JS file, you've coded AJAX to send parameters via HTTP request to the PHP file and receive a response. Now, let's delve ...

The CSS transformation is being overridden

Having an issue where I have two functions that both apply a CSS transform to an element using jQuery, but they end up overwriting each other. These functions are called at different times and have no knowledge of each other. An example showcasing the pro ...

Switching to a jQuery IF statement instead of a FOR loop allows for more streamlined

I recently made a request to sqlite and am fetching data using the code snippet below: var rows = results.rows; alert(rows.length); for (var index = 0; index < rows.length; index++) { var x = rows.item(index); $( ...

Creating anchor links with #id that function correctly in an Angular project can sometimes be challenging

My backend markdown compiler generates the HTML content, and I need Angular to retrieve data from the server, dynamically render the content, and display it. An example of the mock markdown content is: <h1 id="test1">Test 1<a href="#test1" title ...

Is there a way to verify if an email is already registered within a MERN stack application

I am in the process of creating a registration form and need to verify if an email already exists within the system. Below is the React code snippet showcasing the structure for better understanding. In the schema, emails are defined as unique. AuthContr ...

Validating various Google Sheet tabs in real-time

I am currently working on a script for validating localization tests in Google Sheets and I have run into some challenges with the logic. The main goal of the script is to 1) Go through all tabs, 2) Identify the column in row 2 that contains the text "Pass ...

Looking for a way to incorporate or locate additional files within nodejs?

I am attempting to invoke my JavaScript function from my Node.js script, however I am encountering an Uncaught ReferenceError: module is not defined issue. Within my server, I have the following: require('/public/js/script.js')(); foo(); M ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

Implement real-time reporting functionality in Selenium

I have been working on implementing a run-time reporting mechanism for my automated test cases created using Java with Selenium and TestNG. The test results and details are stored in a MySQL database. Although I can successfully insert the test results in ...

Ensuring form input validity in real-time using jQuery's keyup event

I've been working on a form where the user can fill in an input and press enter to move to the next field. Although I have managed to get the functionality to show the next div, I am facing issues with validation... // Moving to next div on Enter ...

Struggling to align Social Media Share Buttons in inline format for a website

I'm having trouble aligning these social media share buttons with my inline list. I tried using vertical-align: top; on the <li> element, but it didn't work in Chrome. You can view the page here: Here is the full HTML/CSS code: <!DOCT ...

What is the best way to modify the selection text background with CSS?

Does anyone know the method for modifying the selection text background in CSS? Many modern websites opt for a personalized background color instead of the traditional blue? ...