How To Select Parent Element Via Children In CSS?

In CSS, selecting a parent element directly from a child element is not possible using just CSS. CSS operates in a cascading manner, meaning styles are applied from the top of the document tree down to the specific element you’re targeting.

But you can achieve this with the help of the CSS :has() pseudo-class. This pseudo-class selects an element (parent) if it contains a specific element (child) or satisfies a given selector. Here is an example:

Example of the CSS :has()

In the following code you can see there are two <div> with the "parent" class, but the CSS border: 2px solid red; will apply to the .parent elements that has (contains) the .child element.

<style>
    .parent:has(.child) {
        border: 2px solid red;
    }
    .child {
        border: 2px solid blue;
    }
</style>

<div class="parent">
    <p class="child">Child Element 1</p>
</div>

<div class="parent">
    <p>Child Element 2</p>
</div>
CSS selecting element if it contains specific element

Select Parent Element Via Children In JavaScript

In JavaScript, you can select a parent element directly from a child element using the parentElement property of the child element. Here is an example:

<style>
    .green-border {
        border: 2px solid green;
    }
</style>

<div class="parent">
    <span class="child">Child Element</span>
</div>

<script>
    // Get the child element
    const childElement = document.querySelector('.child');
    const parentEl = childElement.parentElement; // Selecting the parent element
    parentEl.classList.add('green-border'); // Adding Class to the parent element
</script>
Selecting parent element directly from a child and applying css to the parent