Tips for concealing a div in JavaScript when other divs are not present

Is there a way to hide the title div if related divs are not present in the HTML structure?

This is the main HTML structure:

<div class="row parent">
    <div id="title-1" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-11" class="col-md-6 mb-4 child">
        ... Content ...
    </article>    
    <div id="title-2" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-21" class="col-md-6 mb-4 child"> 
        ... Content ...
    </article>    
    <article id="child-22" class="col-md-6 mb-4 child"> 
        ... Content ...
    </article>    
</div>

After filtering the content:

<div class="row parent">
    <div id="title-1" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-11" class="col-md-6 mb-4 child">
        ... Content ...
    </article>
    <article id="child-12" class="col-md-6 mb-4 child"> 
        ... Content ...
    </article>
    <div id="title-2" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
</div>

If the #child-21 and #child-22 layers are not shown, I want to hide the #title-2 div.

One possible solution I thought of is to create a loop to look for .child pages by ID that start with the same number as the corresponding title div and hide it. However, I'm not sure about how to use wildcards in the references to the id...

Any suggestions on the best way to achieve this using javascript?

Thank you,

Answer №1

Iterate over the titles, converting the ID of each title to the prefix of its corresponding children. Next, check if there are any elements with that specific ID type and toggle the visibility of the title accordingly.

document.querySelectorAll(".prov-title").forEach(title => {
  let child_prefix = title.id.replace(/^title-/, 'child-');
  if (document.querySelector(`.child[id^="${child_prefix}"]`)) {
    title.style.display = 'block';
  } else {
    title.style.display = 'none';
  }
});
<div class="row parent">
  <div id="title-1" class='col-12 prov-title'>
    <h2>Category 1</h2>
  </div>
  <article id="child-11" class="col-md-6 mb-4 child">
    ... Content 11 ...
  </article>
  <article id="child-12" class="col-md-6 mb-4 child">
    ... Content 12 ...
  </article>
  <div id="title-2" class='col-12 prov-title'>
    <h2>Category 2</h2>
  </div>
</div>

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

Excessive iterations occurring in JavaScript for loop while traversing an array

After addressing the issues raised in my previous inquiry, I have made significant progress on my project and it is now functioning almost exactly as intended. The main purpose of this website is to iterate through the World Of Tanks API to generate cards ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

What You See Is What You Get editor options

CKEditor is a fantastic HTML editor, but I've encountered an issue when pasting HTML structure and switching to WYSIWYG mode. The editor automatically reformats the HTML structure, causing unexpected changes to the original layout. I'm intereste ...

The canvas map has an unseen boundary on the right, causing all other div sections to be

When I set the width of my google map canvas to 80%, the map itself fills that percentage but leaves a wide space to the right of the canvas, taking up the remaining 20% of the screen. This creates an issue because my div cannot be placed in that space. ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

Troubleshooting issue: Dropdown menu malfunctioning after using replaceWith() and appendTo()

I could really use some assistance. Admittedly, my knowledge of php, js, jquery, and similar languages is limited. I am currently working on a small web application where users fill out a form with specific requests, the data is then stored in a database, ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

Retrieve targeted information from MySql using jQuery AJAX Success

I've got this AJAX code set up to retrieve data from MySQL and display it in the Success block. $.ajax({ type:"POST", url:"index.php", success: function(data){ alert(data); } }); This is my Query $sql ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

How can I alter the columnWidth setting in Masonry when detecting a different screen width or window width?

I am currently working on adjusting the layout of my masonry script to respond accordingly when the browser window or screen width drops below a certain threshold. However, I am running into issues as it seems to break whenever I try to make this adjustmen ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

What is the best way to handle multiple promises when loading a state in Angular?

When loading the /home state, I need to retrieve all users from the database in order to customize the home controller and view based on the logged-in user. Currently, in the :resolve section of the state configuration, I am fetching all 'posts' ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

Extracting information from a Weather API and sharing it on Twitter

Can anyone help me troubleshoot my Twitter bot setup for tweeting out city temperatures? I attempted switching to a different API, but nothing seems to be resolving the issue. console.log('initiating twitter bot...') var Twit = require('t ...

Storing input field values in JavaScript using the onchange event handler.Would you like a different revision

I am looking to calculate the area by multiplying width and height entered into input fields, and then display the result. Any guidance would be greatly appreciated. Thank you! Here is my current code. const width = document.querySelector("#width"); con ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Introducing random special characters into currency symbols during the process of exporting data to a CSV file

I'm encountering a strange issue when exporting data to CSV files that contain a currency symbol. An extra junk character is being added to the data alongside the currency symbol. For example, if my data is: France - Admin Fee 1 x £100 The result I& ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Conceal the loading image once the AJAX function has been successfully

I've been trying to figure out a way to load heavy images after an ajax call using animated GIF as a pre-loader, but haven't found a satisfactory solution yet. Here's the code snippet I'm currently using: function loadProducts(url) { ...

Having trouble making my Navbar fully responsive for mobile. Can't seem to get the Nav-links to display correctly. Any advice on what

I need some help adjusting my navbar to fit on mobile screens. While I can make the logo shrink, I'm struggling to change the size of the links so that the navbar doesn't get cut off. Below is the code for my Navbar and the corresponding CSS. N ...