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

Using ASP.NET MVC to generate dynamic CSS styles

I am seeking a solution that will allow me to achieve the following objectives: Retrieve dynamically generated CSS from an action method Select a CSS file based on request parameters or cookies Utilize a tool for combining and compressing (minifying) CS ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...

Website issues being displayed by Internet Explorer

Greetings! Let me begin by saying how wonderful this page is - I have already found many answers here before. Please forgive any errors in my English :) In my efforts to optimize my website for SEO and increase its speed, I made several changes. The site ...

Implementing Sass mixin transition to specifically add transition-delay - a comprehensive guide

As I continue to enhance my front-end development skills and practice Sass to optimize my CSS code, I encountered a roadblock. After exploring resources and tutorials online, I created a global mixin in Sass named 'transition'. Here is the code: ...

design facebook type box scroll bar

After extensively searching through various stackoverflow answers in an attempt to change the CSS for a Facebook likebox scrollbar, I have had no success. Below is the code that I am currently using: <div id="fb-root"></div> <script>(fun ...

The image is non-adjustable to different screen sizes

Currently, I am in the process of revamping a friend's website using Next.js and Tailwind. However, I've encountered a challenge with the background image specifically on iPhones. While it appears fine on browsers like Chrome and Safari as well a ...

Unable to retrieve HTML code from a webpage using its URL address

Currently, I am trying to retrieve the HTML code of a specific webpage located at . My initial attempts using HttpClient were unsuccessful due to exceeding request processing time. It seems like this website may have anti-bot protection in place. I attempt ...

The functionality of bootstrap.styl malfunctions during the parsing process in stylus

I am attempting to incorporate stylus, a css preprocessor, with twitter bootstrap version 2.04. Upon downloading boostrap, I execute the command "stylus --css < bootstrap.css > bootstrap.styl" to generate a bootstrap.styl file. However, upon trying t ...

I have to define a specific identifier in Django so that I can easily incorporate it into Bootstrap later on

I am working on creating a portfolio in Django. I have a section in my HTML code that connects to my jobs list in Django using {% for ... %} in order to display images, summaries, and titles of my projects. However, there is an ID within this div that refe ...

Updating Select Options with Multiple Values using Javascript

My goal is to update the selected value of multiple select elements simultaneously using JavaScript. However, I am facing an issue where my script only updates one select element instead of all of them on the page. Unfortunately, I cannot modify the id att ...

HTML: Checkbox not responding to unchecked value... malfunctioning

I am encountering an issue with setting the Checked / Unchecked value of a checkbox. The problem I'm facing is that when the checkbox is unchecked, it returns an empty string. Any thoughts on how to solve this? Here's what I have done so far: ...

Why isn't my heading showing up as expected in my document?

Can anyone help me understand why my title appears so low on certain screens? I've previously tried removing the negative margin when the title was hidden, but now it's positioned too far down. Here is the link to my webpage: ...

The onclick event in JavaScript is unresponsive on mobile devices

Our website is powered by Opencart 1.5.6.4 and the code snippet below is used to add items to the shopping cart. <input type="button" value="<?php echo $button_cart; ?>" onclick="addToCart('<?php echo $product['product_id']; ?&g ...

Why must the sidebar be displayed horizontally on the smartphone screen?

I've been struggling to make the sidebar menu on my smartphone display horizontally with icons at the top and text at the bottom. I've tried using flex and other methods, but it still doesn't work sideways. Am I missing something? const s ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Please select the option to choose all values

Currently, I am working on implementing a select option feature on my webpage. I have integrated PHP into it to ensure that the selected option remains unchanged after submission. My goal is to include a value of "any" so that when the user chooses "ANY," ...

Will the identifier "id" be considered unique if the element with the matching id has its display property set to "none"?

Imagine you have a DIV element in your document with the id "row". Now, if you add another DIV with the same id and change the display property of the first DIV to "none", does the id of the second DIV become unique? ...

What is the best way to distinguish Xpath when dealing with several elements that share identical attributes and text?

I need to find and click on the link labeled "Customer One". The current xPath I am using is: //div[contains(@class,'client-info') and contains(div/text(),'Customer')] When using Firepath, this xPath returns four separate elements (I ...

Is it possible for me to create a Pomodoro clock similar to this one?

Can you provide guidance on creating a Pomodoro clock similar to this design: https://i.sstatic.net/qhd1Z.png As time progresses, the arrow should move around causing the circumference of the circle to increase. What approach or library would you recomm ...