Explain Codes LogoExplain Codes Logo

A CSS selector to get the last visible div

javascript
prompt-engineering
best-practices
responsive-design
Anton ShumikhinbyAnton Shumikhin·Jan 28, 2025
TLDR

To pinpoint the last visible div using CSS, apply :not() and attribute selectors to bypass hidden divs:

div:not([style*="display: none"]):not([hidden]):last-of-type { /* Your secret stylesheet recipe goes here */ }

When visibility is dynamic, use JavaScript to sort visible divs:

let lastVisibleDiv = Array.from(document.querySelectorAll('div')) .reverse() .find(div => window.getComputedStyle(div).display !== 'none');

Enhancing CSS with JavaScript

CSS is effortlessly elegant, but its static nature struggles with dynamic content. That's when JavaScript steps in and saves the day, adding dynamicity to the mix:

function getLastVisibleDiv() { return Array.from(document.querySelectorAll('div')) .reverse() .find(div => div.offsetParent !== null); } // Usage let lastVisibleElement = getLastVisibleDiv(); // Make it pretty! if (lastVisibleElement) { lastVisibleElement.classList.add('highlight'); }

We tapped into offsetParent to determine if the div is visible within the document. No more false alarms—it's more reliable than checking inline styles or CSS properties.

CSS and JavaScript: A dynamic duo

Complement your CSS skills with JavaScript to manage dynamic content. Let's delve deeper into how these languages interact when visibility gets a little playful.

Adapting to visibility changes

Inline styles and attribute selectors (e.g., [style*="display: block;"]) work well until your content starts playing hide-and-seek. Unleash the JavaScript might for a comprehensive approach to handle sneaky display changes.

Harnessing jQuery's power

Not an alien to jQuery? It streamlines the process dramatically, reducing JavaScript to this one-liner:

let $lastVisibleDiv = $('#your_container > div:visible:last');

Wrangling with classes and IDs

Classes and IDs can act as reliable signposts when you're navigating through a jungle of divs. They help focus your JavaScript or jQuery spotlight on a meaningful subset of elements.

Advanced maneuvers

Getting modular

Wrap those divs in a container. It cleans up the selection process and adheres to the best practices of HTML structuring.

Going beyond visibility

The CSS property filter: blur(3px) can hint at interactive states, offering a subtle nod to user experience.

CSS's limitations, JavaScript to the rescue

The CSS [style*="display:none"] selector doesn't cover visibility alterations via classes or external stylesheets. JavaScript's here to ensure no visibility changes slip through the cracks.