Identifying whether a class exists on the same level using a selector

Snippet display:

$( document ).ready(function() {
//$(".tree-node").parents('.tree-child-folders').css("color", "red");
  //$(".tree-collapsed:has(.tree-child-folders)").css("color", "red");
  $(".tree-node > .tree-collapsed:has(.tree-child-folders)").css("color", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST1</span>
  <span class="tree-collapsed">CHANGE COLOR</span>
  <span class="tree-test">TEST3</span>
</div>

<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST4</span>
  <span class="tree-other">TEST5</span>
  <span class="tree-test">TEST6</span>
</div>

<div class="tree-node">
  <span class="tree-line">TEST7</span>
  <span class="tree-collapsed">TEST8</span>
  <span class="tree-test">TEST9</span>
</div>

My goal is to style the <span> elements with classes .tree-collapsed and .tree-child-folders on the same level with the color red. Wondering if we can achieve this using CSS only.

Answer №1

To achieve this effect using CSS, you can utilize the general successor sibling selector ~ (which selects elements that come after a specified element, but not necessarily immediately after) or the next sibling selector +

.tree-node > .tree-child-folders ~ .tree-collapsed {
color: red;
}
<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST1</span>
  <span class="tree-collapsed">CHANGE COLOR</span>
  <span class="tree-test">TEST3</span>
</div>

<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST4</span>
  <span class="tree-other">TEST5</span>
  <span class="tree-test">TEST6</span>
</div>

<div class="tree-node">
  <span class="tree-line">TEST7</span>
  <span class="tree-collapsed">TEST8</span>
  <span class="tree-test">TEST9</span>
</div>

Answer №2

If you're looking to achieve this using jQuery instead of CSS, you can utilize a sibling combinator, assuming the .tree-child-folders element appears before the .tree-collapsed element. One approach is to use the "subsequent sibling combinator" (~):

$(document).ready(function() {
    $(".tree-node > .tree-child-folders ~ .tree-collapsed").css("color", "red");
});

Here's a Live Example:

$(document).ready(function() {
    $(".tree-node > .tree-child-folders ~ .tree-collapsed").css("color", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST1</span>
  <span class="tree-collapsed">CHANGE COLOR</span>
  <span class="tree-test">TEST3</span>
</div>

<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST4</span>
  <span class="tree-other">TEST5</span>
  <span class="tree-test">TEST6</span>
</div>

<div class="tree-node">
  <span class="tree-line">TEST7</span>
  <span class="tree-collapsed">TEST8</span>
  <span class="tree-test">TEST9</span>
</div>

If the order is not consistent, you may need to resort to looping through the elements:

// Find all `.tree-node > .tree-collapsed` and iterate through them
$(".tree-node > .tree-collapsed").each(function() {
    var $this = $(this);
    // Check if this parent also has a `.tree-child-folders` element
    if ($this.parent().find(".tree-child-folders").length) {
        // If yes, change the color to red
        $this.css("color", "red");
    }
});

Here's a Live Example of the looping method:

$(document).ready(function() {
    // Find all `.tree-node > .tree-collapsed` and iterate through them
    $(".tree-node > .tree-collapsed").each(function() {
        var $this = $(this);
        // Check if this parent also has a `.tree-child-folders` element
        if ($this.parent().find(".tree-child-folders").length) {
            // If yes, change the color to red
            $this.css("color", "red");
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST1</span>
  <span class="tree-collapsed">CHANGE COLOR</span>
  <span class="tree-test">TEST3</span>
</div>

<div class="tree-node">
  <span class="tree-child-folders tree-line">TEST4</span>
  <span class="tree-other">TEST5</span>
  <span class="tree-test">TEST6</span>
</div>

<div class="tree-node">
  <span class="tree-line">TEST7</span>
  <span class="tree-collapsed">TEST8</span>
  <span class="tree-test">TEST9</span>
</div>

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

Is there a way to use jQuery to verify if an LI element contains a parent LI element?

Struggling with customizing the comments section of a WordPress theme? Utilizing jQuery for styling can be tricky, especially when dealing with nested UL elements like admin comments. The challenge lies in traversing the DOM structure to target specific el ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

What is the best way to create a border for the active class nav-item in Bootstrap 4?

I am facing an issue with changing styles in the nav-item. I have created a separate style sheet and added the necessary code to make the changes. Surprisingly, the changes are reflecting well in Internet Explorer but not in Firefox. Can anyone guide me on ...

I'm having trouble getting my footer to stay at the bottom of the page

Struggling to get my footer to stay at the bottom on my blog pages, no matter what I try: Every time the social media section appears, the footer slides up... Can't figure out why... Appreciate any assistance! ...

The MUI component with hideBackDrop={true} is preventing me from clicking outside of the Drawer component to close it

I implemented a Drawer component which opens when an icon on the Map is clicked. The drawer menu appears along with a backshadow that drops over the map. Interestingly, clicking on the map while the backshadow is displayed closes the drawer without any i ...

The use of HTML in a more minimalist "less" style

After observing Less code, I've found it to be quite straightforward and efficient in comparison to Cascading Style Sheets. Is there a similar option available for HTML? ...

Troubleshooting problem with CSS overflow and absolute positioning on Android Browser

Our mobile web app was created using a combination of JQuery Mobile, PhoneGap, and ASP.net MVC. It is designed to function smoothly on both iOS and Android devices regardless of the browser being used. We have conducted tests on various devices and everyth ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...

To make a JavaFX label stand out, simply prepend a vibrant red asterisk at the start of

I'm facing a challenge with my SceneBuilder project. I have developed a scene that consists of several labels, and I want to highlight some of them by adding a red asterisk at the beginning of their text. Unfortunately, I haven't been able to fin ...

Modify the standard placement of choices in MUI

Currently, my UI is powered by MUI. I have various options displayed in the image below: https://i.sstatic.net/YKoyV.png Everything looks good so far. However, I wish to reposition the options container further down. (It is currently set at top: 64px ...

What is the most effective way to align a thumb to the left and content to the right?

What is considered the optimal method for positioning an image to the left with two text fields to the right of it? Is using floats or positioning better? <li> <a href=""> <img src=""THUMB HERE /> </a> <a href=""> TITLE </ ...

Issue with ng-repeat not being filtered

Utilizing Salvattore (a masonry-like grid) within my Angular application, but encountering issues with the filter option in ng-repeat. It seems that Salvattore encapsulates each repeated item in an individual div to structure the grid (in this case, div.co ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

Is there a way to overlay a div on a particular line within a p element?

Within this paragraph lies a collection of text encapsulated by a < p > tag. When this content is displayed on the page, it spans across 5 lines. My objective is to creatively style and position a < div > tag in order to highlight a specific li ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

Refresh Google Maps without showing gray areas on the screen

Currently, I am utilizing the Google Maps API v3 in javascript and frequently reloading the map using an app.get while also incorporating layers and bookmarks via mongodb. Whenever I reload the map to erase everything, a gray background appears in the div ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

Adjusting the size of an element in Angular JS as a textarea expands

I have created a directive that allows for writing and previewing comments, similar to the conversations in Github. The directive consists of two HTML elements: a textarea and a div (utilizing angular-marked). My goal is to dynamically resize the div as I ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

Utilizing a jQuery DataTable extension on dynamically created tables through ASP.NET

Here is what I need: On my ASPX page, I am importing data from a spreadsheet using fileUpload and dynamically creating an ASP.NET table. The structure and data of the table are determined by the imported file, and my application does not know the number o ...