how can I modify the css style of an html element only when a specific sibling is present?

After searching through the MDN CSS documentation, I was unable to find any Combinators that can target the specific element I want to style.

/* second-span red when first-span is present */
[first-span] ~ [second-span] {
  color: red;
}

/* first-span blue ONLY when second-span is present */
/* HOW TO ? */
[first-span] /* combinator doesn't exist */ {
  color: blue;
}
<p>
  <span first-span="">I am #1</span><br>
  <span second-span="">I am #2</span>
</p>

<p>
  <span first-span="">I am #1</span>
  <!-- no second span -->
</p>

<p>
  <span second-span="">I am #2</span>
</p>

I'm attempting to apply a style to an element only if a specified sibling is found among the neighboring elements below it.

In the provided code snippet, the first CSS statement successfully styles an element if the left-hand selector is located among preceding siblings. However, I'm struggling to find a combinator that achieves the opposite effect.

Is there a way to accomplish this task?

Answer №1

By utilizing the combination of nth-child with other pseudo classes, you can specifically target elements within sets of elements with defined lengths.

The use of the <br> tag as a child element of <p> adds a layer of complexity, but it should still function according to your requirements:

/* This rule will style the first element out of three nested children in a p tag in blue */
p span:nth-child(1):nth-last-child(3){
  color: blue;
}

/* This rule will style the third element out of three nested children in a p tag in red */
p span:nth-child(3):nth-last-child(1) {
    color: red;
}
<p>
  <span first-span="">I am #1</span><br>
  <span second-span="">I am #2</span>
</p>

<p>
  <span first-span="">I am #1</span>
  <!-- no second span -->
</p>

<p>
  <span second-span="">I am #2</span>
</p>

This code snippet targets the first and last elements out of a set of three.

Answer №2

If you want to keep your code clean, you can utilize jQuery in the following way:

if($('p > span:nth-of-type(2)').length) {
   $('p > span:nth-of-type(1)').css('color','red');
}

Learn more about checking if an element exists in jQuery

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

What distinguishes submitting a form from within the form versus outside of it?

When the code below, you will see that when you click btnInner, it will alert 'submit', but clicking btnOuter does not trigger an alert. However, if you then click btnInner again, it will alert twice. Now, if you refresh the page: If you first ...

Optimizing the appearance of an unordered horizontal list in the most effective manner

When attempting to make lists horizontal and hide default bullets, is it necessary to apply {display:inline} and {float:left} to both the <li> tags or would just one of these properties suffice? <ul> <li><a href="#">First item< ...

Instruct the VirtualHost DocumentRoot to redirect the HTML from "/" to a subfolder within the WWW directory

Apologies for repeating this question, but despite extensive discussions on the topic, I am struggling to find a solution for setting up a local development environment using VirtualHost. Currently, I am using XAMPP Portable for Windows, but I believe the ...

Why is my jQuery not selecting the classes from this iframe?

I'm attempting to retrieve all classes with the name "titular_portada". There are many, but for some reason it's not functioning: <!DOCTYPE html> <html lang="es"> <head> <link rel="stylesheet" href=&q ...

What is the best way to select the destination folder for output in Webpack?

Whenever I run webpack using "webpack --mode development", it generates a dist folder and places the bundle.js file inside it. My aim is to have it created and placed in the same directory instead. How can I achieve this? module.exports = { entry: " ...

Show the jQuery code block as HTML within a textarea

I'm in need of a way to display script reference code in a textarea for easy copying by users. <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"/> Even though I am using jQuery, all the solutions I ...

A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out. Below is the code snippet: import React from "react"; import ReactDOM from "react-dom"; import { TextField, Bu ...

Is there a way to trigger an ajax call specifically on the textarea that has been expanded through jQuery?

Whenever I expand a textarea from three textareas, all three trigger an ajax call. Is there a way to only call the ajax for the specific expanded textarea? I tried using $(this).closest('textarea').attr('id'), but it didn't work. A ...

Neglecting images on Zoom

Looking to scale up the elements on an HTML page by 50%, without affecting the resolution of images. Despite trying zoom: 150% in CSS3, it ends up zooming pictures as well, resulting in blurry visuals. Is there a way to enlarge all HTML components while ...

A guide on extracting a div element without a class using Html Agility Pack

Can you help me extract the text 'Galatasaray.' from the HTML code below? I'm not sure how to specify it properly. <div class="dRib1"> <h2>Information</h2> </div> <div>Galatasaray.</div> ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...

Is there a way to conceal the parent element when the child element is hidden from view?

Wanting to remove the stars badge in the review section of a Shopify store when there are 0 reviews for the product. The goal is to have the badge appear automatically once a review is received. Here's the code snippet: HTML <div class="spr- ...

The second div element remains unselected in jQuery

Below is the example of an HTML structure: <span id="17">yes here</span> <div class="PricevariantModification vm-nodisplay"></div> <div class="PricesalesPrice vm-display vm-price-value"> <span class="a"></span> ...

Styling emails with CSS: Tips for customizing fonts

I've been experimenting with setting a personalized font for an email. Within the HTML code of the email, I included the fonts using this snippet: <head> <style> /* latin-ext */ @font-face { font-family: &ap ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

How can I change the background color of the initial word in a textbox?

In my HTML, I have a text box input. While I am familiar with how to use CSS to set the background color of the entire textbox using background-color, I am wondering if it is possible to specifically target and change the background color of only the first ...

Ways to apply a border-bottom to tr elements without affecting td elements

Is there a way to add a bottom border to <tr> elements without affecting <td> cells that have no border? I attempted the following approach, but setting border: 0 for <td> overrides the border for all <tr> elements as well, leaving ...

What is the best way to create a unique shadow effect for a container in Flutter?

I am facing a challenge with my screen layout that uses GridView.builder with crossAxisCount: 3. In the itemBuilder, I am returning a Container with shadows on the left, right, and bottom, but so far, I have not been able to achieve the desired outcome. H ...

What is the significance of the .jpg?t= in the URL?

This webcam image displays the code ?t=1512496926. What exactly does this code signify? Could it be related to time? Is it just a random string of characters? https://i.stack.imgur.com/ZAZMy.jpg ...

Loading Kendo JS on the client side proves to be rather time-consuming

Working on my project, I have encountered a problem with the kendo ui scheduler where the downloading of the kendo js and css files on the client side is causing slowness on our website. To address this issue, we are attempting to download the kendo js and ...