Explain Codes LogoExplain Codes Logo

Apply CSS styles to an element depending on its child elements

javascript
dom-manipulation
css-selectors
javascript-techniques
Anton ShumikhinbyAnton Shumikhin·Dec 8, 2024
TLDR

JavaScript provides a handy solution for manipulating parent states and classes based on child conditions. In this quick example, we’re adding a .styled class to the parent if it has a child.

document.addEventListener('DOMContentLoaded', () => { const parent = document.querySelector('.parent'); if (parent.querySelector('.child')) { parent.classList.add('styled'); } });

Pair it up with a CSS rule for the newly added class:

.parent.styled { color: #007bff; /* An example of styling */ }

Voila! You've just styled the parent by checking whether it has a child.

JavaScript comes to the rescue

JavaScript is the knight in shining armor when you need to evaluate the Dynamically-Updated-Really-Messy(DOM) and change styles based on certain conditions.

More than meets the eye with JavaScript and CSS

JavaScript can assess specific conditions and not just the presence of a child, dynamically adding CSS classes to the parent.

const parent = document.querySelector('.parent'); if (parent.querySelectorAll('.child').length > 2) { // If the kids are triplet. parent.classList.add('many-children'); // Call a babysitter! }

In your CSS, link the many-children class to the desired style.

.parent.many-children { box-shadow: 0px 0px 15px rgba(0,0,0,0.2); // Adding some shadow! Spooky! }

CSS :has() - A beacon of hope...soon!

The :has() pseudo-class is the light at the end of the tunnel. It allows you to style an element based on its child elements, but currently has limited browser support.

.parent:has(> .important-child) { background-color: #ffeb3b; // Becomes yellow when the special kid shows up! }

Grappling with complex DOM structures: The jQuery escapade

When CSS falls short, jQuery shines in the spotlight. Its powerful selectors enable styling parent elements based on their child elements.

$('.parent:has(.special-child)') // Any descendant `.special-child` .addClass('highlight');

And the CSS for this scenario:

.parent.highlight { outline: 2px dashed #4caf50; // A little dazzle never hurt! }

Selectors smackdown: CSS vs. jQuery

Here's a comparison of CSS and jQuery approaches, offering solutions to a variety of scenarios:

FeatureCSSjQuery
Immediate child.parent > .child$('.parent > .child')
Any descendant.parent .child$('.parent .child')
Conditional style based on child.parent:has(.child)*$('.parent:has(.child)')

*Future feature with salute to our beloved browsers

Choosing the perfect tool

CSS - Simple and declarative

CSS is best employed when the relationship between the parent and child is known and doesn't change.

.parent:hover > .child { display: block; // Kids, you can come out and play! }

JavaScript - The Dynamic Performer

JavaScript springs into action when the DOM structure or state changes:

window.addEventListener('resize', () => { document.querySelectorAll('.parent').forEach(parent => { if (window.innerWidth > 768) { parent.classList.add('wide-screen'); // Display wide when screen is wide. } else { parent.classList.remove('wide-screen'); // Daughter? Shrunk the screen! } }); });

jQuery - The Complex Artist

Handle intricate scenarios with jQuery. It ascends when you have nested elements or need to conditionally apply styles:

$(window).on('load scroll', () => { $('.parent:has(.in-view)').each(function() { if ($(this).find('.child').visible()) { $(this).addClass('active'); // If I see you, you get the class! } }); });