What is the best way to assign a class to a child element when the rest of the children are not visible

Looking for a CSS-only solution, I have a simple task involving filtering div elements. The goal is to display an error message when none of the filtered divs match the selected criteria.

HTML Structure:

<div id="listHolder">
    <div class="listItem" data-filter-class="["filter1"]"></div>
    <div class="listItem" data-filter-class="["filter2"]"></div>
    <div class="listItem" data-filter-class="["filter1"]"></div>
    <div class="listItem" data-filter-class="["filter4"]"></div>
    <div class="errorItem">Nothing to display here</div>
</div>

What I am trying to achieve:

To determine if all listItem divs that do not match filters are also marked as inactive, in order to show the errorItem with style display:block.

FYI, using the Wookmark plugin and LESS for this setup.

Answer №1

Indeed, it is feasible: http://jsfiddle.net/rudiedirkx/7b1kyfz3/3/

If you want to conceal the last item when a previous item is not hidden:

.listItem:not(.inactive) ~ .errorItem {
    display: none;
}

In the demonstration, JavaScript is only used to toggle the inactive class, not for managing the display of the errorItem.

I do concur with the experts here that using JavaScript might be more efficient in this scenario. After all, you are already utilizing it.

Answer №2

The issue you are facing lies within the specific requirement at hand:

In order to determine if all div elements with the listItem class also possess the inactive class, and subsequently apply the errorItem class with the style of display:block.

While it is possible to set a styling for the final <div> based on its preceding siblings, conducting an exhaustive check for the presence of the inactive class among all divs poses a challenge without prior knowledge of their quantity. A potential solution involves utilizing the sibling combinator (+) along with a rather complex selector:

.errorItem {
    display: none;
}
.listItem.inactive + .listItem.inactive + .listItem.inactive + .listItem.inactive + errorItem {
    display: block;
}

However, this approach becomes impractical, especially in scenarios where the number of preceding elements before the .errorItem element varies dynamically.

If there exists a different class name assigned to elements that meet the specified criteria—such as active—the solution can be simplified using the following method:

.errorItem {
    display: block;
}

.listItem.active ~ .errorItem {
    display: none;
}

Furthermore, as mentioned in the comments, certain browsers support the negation operator which allows for a selector like this:

.errorItem {
    display: block;
}

.listItem:not(.inactive) ~ .errorItem {
    display: none;
}

In general, employing JavaScript would be recommended to facilitate such functionality, particularly considering that Wookmark implies some level of JavaScript (if not jQuery) usage on the website.

Vanilla JavaScript implementation could look something like this:

function hasPrecedingSibling(elem, state) {
    if (!state) {
        return false;
    }
    var found = false,
        cur = elem;
    while (cur.previousElementSibling && !found) {
        if (cur.classList.contains(state)) {
            found = true;
        } else {
            cur = cur.previousElementSibling;
        }
    }
    return found;
}

[].forEach.call(document.querySelectorAll('.errorItem'), function(err) {
    err.style.display = hasPrecedingSibling(err, 'active') ? 'none' : 'block';
});

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 materials are required in order to receive messages and information through my Contact page?

Currently, I am pondering the optimal method for gathering information from my Contact page. I have already created a form; however, I'm unsure how to send the gathered data to myself since I am relatively new to Web development. Angular is the framew ...

Problem arises when the DIV elements are not expanding horizontally together

Struggling to create a round corner box using divs. I have been working on it all day and can't figure out what I'm missing. If anyone could help me spot the issue, that would be great. I want the 'header' and 'footer' to exp ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Why is the dropdown bootstrap component not functioning in the browser?

The dropdown-item in my code, taken from the Bootstrap site, is not working properly. The toggle displays but the item does not. What could be causing the Bootstrap dropdown component to malfunction in the browser? Are there any issues with my CDNs? ...

A guide on troubleshooting anchor links that are occasionally functioning properly, but at other times directing users to the incorrect destination

I must admit that I am a total beginner when it comes to coding. I hope this is the right platform to share my confusion. Using Wordpress Gutenberg, I attempted to craft a lengthy article. A main table of contents was placed near the top of the page (done ...

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

Extend the height of bootstrap 5.2.0 row/column to reach the bottom of the page

I'm having difficulty extending the left navigation section to reach the bottom of the page while remaining responsive. Despite trying various solutions like h-100, flex-grow, min-vh-100m self-align: stretch, nothing seems to solve the issue. Check o ...

Tips for preventing images from stretching the width and height of my HTML

I am facing an issue with my SVG files positioned as "absolute" on my page. When they are close to the corners of the page, they end up expanding the width of my Container element (using Material UI React). I have tried setting "maxWidth":"100vw" on the ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...

Transferring data between two HTML files through the POST method

Is there a way to pass two values (parameters) from one HTML page to another without displaying them in the URL, similar to using the POST method? How can I retrieve these values on the second HTML page using JavaScript, AJAX, or jQuery? For example: cli ...

Create a full-screen layout with a Bootstrap 5 column grid and a sleek navbar

Can you help me modify this design using Bootstrap rules while keeping the original CSS files intact? I need to make these 5 cards (columns) full width with a navbar. Issue 1: I always see a vertical scroll bar on desktop. Issue 2: The Navbar doesn' ...

Choose an XPath formula that will target every single element, text node, and comment node in the original sequence

How can we write an XPath expression that selects all elements, text nodes, and comment nodes in the order they appear in the document? The code below selects all elements but not text nodes and comment nodes: let result = document.evaluate('//*&apo ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Is there an HTML editing tool that has the ability to collapse code blocks by tags and rearrange them?

I'm in search of a text editor or IDE that includes syntax highlighting and allows me to collapse HTML code blocks by tag. I currently use Eclipse, but its "folding" feature only works on top level tags like TABLE, not child tags like TD and TR. Are t ...

How can a block be made to stay fixed and float in a flexbox layout?

There are three blocks within the body of this page. Title bar Content block Bottom block I have employed a flex display for the body layout. My goal is to make the title bar float, meaning it should always remain at the top when scrolling. I attempted ...

Span tag not respecting CSS width property

One of my spans is causing an issue. Here are the styles in question: .form_container .col1che { float: left; width: 4%; text-align: left; } .form_container .col2che { float: left; width: 80%; text-align:left; } .form_container .col3che { float: ...

Unusual phenomenon of overflow and floating point behavior

HTML and CSS Output Example: <div id="float_left"> DIV1 </div> <div id="without_overflow"> DIV2 </div> CSS Styling: #float_left{ float: left; width:200px; background-color: red; } #wit ...

Best practices for coding in HTML and CSS

Creating my first website for an internship has been quite a learning experience. Throughout my training, I was always advised to avoid embedding styles directly into the HTML code. However, now that I am actually developing a site, I can't help but f ...

``There seems to be an issue with background size not functioning properly in

I have successfully implemented a body background image with full width following your previous questions and answers. However, I encountered an issue on Mozilla browser where the image is not scaling to full width. Here is the CSS code I am using: backgr ...