When consecutive DOM elements are hidden, a message saying "Hiding N elements" will be displayed

Provided a set of elements (number unknown) where some elements should remain hidden:

<div id="root">
  <div>              1</div>
  <div class="hide"> 2</div>
  <div class="hide"> 3</div>
  <div class="hide"> 4</div>
  <div>              5</div>
  <div>              6</div>
  <div class="hide"> 7</div>
  <div>              8</div>
  <div class="hide"> 9</div>
  <div class="hide"> 10</div>
</div> 

Hiding the elements with the hide class using CSS is straightforward (.hide { display: none; }). However, the objective is to replace each consecutive section of hidden elements with a replacement element, such as

<div>Some elements were hidden</div>
, or more precisely
<div>N elements hidden</div>
where N represents the number of hidden elements within that specific range (3, 1, and 2 in the provided example). Consequently, the final result would appear as follows:

1, 3 Elements hidden, 5, 6, 1 Element hidden, 8, 2 Elements hidden

Firstly, can this be accomplished exclusively through CSS? Although I cannot conceive of a direct method, there may be inventive individuals proficient in selector usage who could provide a solution :)

If resolved with only CSS is unattainable, does an alternative path exist by adding JavaScript classes + utilizing ::before/::after pseudo-elements? In other words, without modifying any actual DOM elements?

Answer №1

If I were to tackle this issue, my preference would be to utilize Javascript. However, if you are determined to rely solely on CSS, there are a few clever tricks that can help you achieve the desired outcome:

.hide {
 counter-increment: hiddenElements;
 visibility: hidden;
 font-size: 0px; 
}

The use of

counter-increment: hiddenElements;
will automatically increment the value for each hidden element. The caveat is that this method does not function with display: none;. Therefore, I have resorted to employing visibility: hidden; and font-size: 0px; as alternative workarounds to produce a similar effect.

.hide + div:not(.hide):before {
  content: counter(hiddenElements) " element(s) hidden \A";
  white-space: pre;
}

This snippet outputs the number of hidden elements once it encounters a sequence of a hidden element followed by a visible one. It's crucial to have a final (potentially empty) <div></div> in place to ensure this triggers correctly.

.hide + div:not(.hide) + div {
  counter-reset: hiddenElements;
}

Following the display of the total hidden elements count, this code effectively resets the counter on the subsequent div.

A demonstration can be viewed below.

.hide {
 counter-increment: hiddenElements;
 visibility: hidden;
 font-size: 0px; 
}

.hide + div:not(.hide):before {
  content: counter(hiddenElements) " element(s) hidden \A";
  white-space: pre;
}

.hide + div:not(.hide) + div {
  counter-reset: hiddenElements;
}
<div id="root">
  <div>              1</div>
  <div class="hide"> 2</div>
  <div class="hide"> 3</div>
  <div class="hide"> 4</div>
  <div>              5</div>
  <div>              6</div>
  <div class="hide"> 7</div>
  <div>              8</div>
  <div class="hide"> 9</div>
  <div class="hide"> 10</div>
  <div></div>
</div>

While this approach indeed functions, it does come with some minor limitations. In my opinion, pursuing a JavaScript solution would be more advantageous. Feel free to post a question with the JavaScript tag, and I will gladly offer my support there as well.

Answer №2

While the question was not originally tagged with jQuery, I wanted to offer a solution that utilizes it:

$('#container div').each(function() {
  if ($(this).hasClass('hide')) {
    var count = $(this).nextUntil(':not(.hide)').addBack().length;
    $(this).html( count + ' elements hidden')
    $(this).next('.hide').hide()
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="container">
  <div> 1</div>
  <div class="hide"> 2</div>
  <div class="hide"> 3</div>
  <div class="hide"> 4</div>
  <div> 5</div>
  <div> 6</div>
  <div class="hide"> 7</div>
  <div> 8</div>
  <div class="hide"> 9</div>
  <div class="hide"> 10</div>
</div>

Answer №3

Have you considered utilizing the css counter technique?
Explore more about using CSS counters here

#root {
  counter-reset: section;
}

#root > div.hide {
  counter-increment: section;
  width: 0;
  height: 0;
  overflow: hidden;
}

#root > .hide + div:not(.hide):before {
  color: red;
  display: block;
  height: 100%;
  width: 100%;
  content: counter(section) " element hidden";
}

#root > .hide + div:not(.hide) + div {
  counter-reset: section;
}

Check out this live example on JSFiddle


Oops, my bad for misinterpreting the question..
Leaving my previous answer here for reference.


How do you feel about this little hack?

.hide {
  transform: scale(0.0001);
  line-height: 80%;
}

.hide:before {
  content: 'This is hidden';
  transform: scale(10000);
  width: 100%;
  height: 100%;
  display: block;
}

Demo available at: Take a look at this demo link

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

Reactivating a React hook following the execution of a function or within a function in ReactJS

A new react hooks function has been created to retrieve data from an API and display it on the page: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [departments, setDepartm ...

Main menu items failing to display sub menu options

I am in need of assistance as I am facing the same issue on two WordPress twin websites that are using the same theme (Newmagz), which is no longer purchased and therefore not supported. The submenus in the main menu are simply not appearing. I have checke ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

What is the best way to showcase a full-screen overlay directly inside an iFrame?

As I work in HTML, I'm faced with a challenge - my iFrame is only taking up a small section of the screen (referred to as 'World' in the example below). What I want to achieve is creating a full-screen div overlay from that iFrame, but curr ...

ReactJS implementation for selecting names from a dropdown menu

Hello, I am new to using React. I have a dropdown form with a search engine in it that is working perfectly as I need. The only issue is that when I type, for example, AR in the Symbol field, it shows me ARDRBTC as expected, but I am unable to click on it ...

Iterate through the array to verify that the specified conditions are satisfied for each individual item

I am working with an array of items and need to check if they all meet specific criteria. I've created a for loop to iterate through the array, but I'm concerned about its efficiency. Is there a more optimal way to achieve this? let match = 0; ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

Perform activities within a component responsible for displaying a flatlist

I have a component called Post that I'm using to display posts within a FlatList. Currently, the Post component only shows text and images in the Flatlist. However, within the Post component, there are buttons that should have functionality such as de ...

Is the auto-import feature in the new VSCODE 1.18 compatible with nodelibs installed via npm?

Testing out the latest auto-import feature using a JS file in a basic project. After npm installing mongoose and saving an empty JS file for editing, I anticipate that typing const Schema = mongoose. will trigger an intellisense menu with mongoose nodelib ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

Tips for assigning an event to a variable in JavaScript

Here is my javascript code snippet: function drag(ev){ var x= ev.dataTransfer.setData("Text",ev.target.id); } I am trying to pass a variable within this event so that I can perform a specific action. However, the current implementation is not worki ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

The dropdown list is not getting populated with data retrieved from an HTTP response

My experience with making HTTP calls is limited, and I am facing an issue while trying to populate specific properties of each object into a dropdown. Despite attempting various methods, such as using a for loop, the dropdown remains empty. created(){ a ...

The state change in React-Redux does not trigger a re-render

I successfully developed a large react-redux application with an undo feature in one component. While the state updates properly and re-renders the component along with its children, I noticed that the component's position on the page remains unchange ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created: <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-if="comic.item_type === 'b&ap ...

Is it possible to create an input field exclusively for tags using only CSS?

I am currently facing some limitations with a website I am managing. Unfortunately, I do not have the ability to incorporate additional libraries such as custom jQuery or JavaScript scripts. My goal is to customize an input field for tags so that when us ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...