Choose either immediate offspring or immediate offspring of immediate offspring

I am struggling to create a CSS Selector that follows DRY principles.

The selector needs to target elements within a group but not those within a subgroup of the main group.

Elements should only be direct children of the main group or wrapped in an additional element.

In the given DOM, the standard selector would be:

.grp.A > .el, .grp.A > * > .el

To make this more DRY, we can use: :is(.grp.A, .grp.A > *) * .el

Personally, I think the most DRY solution would look something like: .grp.A:is(*, * > *) > .el, but unfortunately, it doesn't work. Do you have any suggestions for improving this further?

console.log([...document.querySelectorAll(".grp.A > .el, .grp.A > * > .el")]);
console.log([...document.querySelectorAll(":is(.grp.A, .grp.A > *) > .el")]);
console.log([...document.querySelectorAll(".grp.A:is(*, * > *) > .el")]);
<div class="grp A">
  <div class="cont">
    <div class="grp B">
      <div class="el noooooo"></div>
    </div>
  </div>
  <div class="el yes1"></div>
  <div>
    <div class="el yes2"></div>
  </div>
</div>

Answer №1

When dealing with CSS selectors, my priority would be on readability rather than conciseness. The initial selector displayed is the most easily readable.

.grp.A > .el, .grp.A > * > .el

In regards to your third attempt, referencing the CSS Level 4 specification:

Default namespace declarations do not impact the compound selector representing the subject of any selector within a :is() pseudo-class, unless that compound selector contains an explicit universal selector or type selector.

I had to review this multiple times, but as I understand it, :is() operates at a global scope, and the selectors within it cannot be based on what precedes them.

I have included an additional example where a compounded selector within :is does not function based on preceding elements.

// Direct child .el of .grp.A or direct child .el of any direct child of .grp.A
console.log([...document.querySelectorAll(".grp.A > .el, .grp.A > * > .el")]);
// Direct child .el of .grp.A or direct child .el of any direct child of .grp.A
console.log([...document.querySelectorAll(":is(.grp.A, .grp.A > *) > .el")]);
// Direct child .el of .grp.A that is any element, or
// that is any element that's a direct child of any element
console.log([...document.querySelectorAll(".grp.A:is(*, * > *) > .el")]);
//.grp.A satisfies criteria of being anything, all equating to .grp.A > .el

// Additional example that compounds don't work for :is()
// Only .A of the two arguments in the :is list works
console.log([...document.querySelectorAll(".grp:is(.A, .A > *) > .el")]);
<div class="grp A">
  <div class="cont">
    <div class="grp B">
      <div class="el noooooo"></div>
    </div>
  </div>
  <div class="el yes1"></div>
  <div>
    <div class="el yes2"></div>
  </div>
</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

Vue error: Uncaught promise rejection - RangeError: The computed value update has exceeded the maximum call stack size

My computed code snippet: computed: { display: { get() { return this.display }, set(newValue) { this.display = newValue } } }, Attempting to update the computed value from a function in ...

The error message that you are seeing is indicating that the `contracts` property of `this.state

Despite having encountered this issue before, I am still struggling to find a solution. The code snippet for fetching data is as follows: async componentDidMount(){ try { const res = await fetch('https://example.com/data.json'); ...

Issue with sidebar display inconsistency when resizing the window

Struggling with the sidebar display issue on mobile, as the menu appears outside the sidebar when resized. Is it feasible to relocate the bar to the top and resize it for a better mobile view experience? Adjusting the navbar's position affects the hea ...

How come I am receiving a null value for isMatch from bcrypt compare even though the two password strings match exactly?

Currently, I am attempting to authenticate a user based on a password. My approach involves using bcrypt compare to check if the user's requested password matches one stored in a MongoDB database. Despite the passwords being identical, I keep receivin ...

What could be causing the discrepancy in sizes of the columns in my multi-column layout?

https://jsfiddle.net/drqjmssy/ Seeking assistance from the linked jsfiddle, I aim to align "div class='main_content'" vertically with "div class='sidebar'". What would be the best approach to achieve this alignment? In case the fiddle ...

The output from the Compute function is not showing up in the TextBox as expected

I'm currently working on an HTML page that contains two textboxes and a button. I've created a Compute function to display the result in one of the textboxes, but unfortunately, it's not functioning as expected. No alerts are appearing on th ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

The CSS toggle feature in the React component is not being implemented as expected

I am currently working on a component that maps over an array and displays a series of buttons that render specific content: export const Bookings = ({bookings}) => { const [selectedBooking, setSelectedBooking] = useState(false); const handleSel ...

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript. View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview However, when the button is clicked, the ...

How can I trigger my function in jQuery after inputting into the jQuery text field?

Looking for advice on implementing a function in jQuery for a text field that is not working as expected. The code works fine when creating a text field in HTML, but encounters issues with the jQuery text field. <!DOCTYPE html> <html> <body ...

Swap out the %20, which signifies a space in the iron router context

I am attempting to substitute the %20, which signifies a space in the URL, with a different character. Router.map(function () { this.route('promos', { path: '/:promo_name', waitOn: function(){ return Meteor.subscribe( ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

Is it possible to utilize a JavaScript variable in this particular scenario and if so, what is the

let myVariable = <?php echo json_encode($a[i want to insert the JS variable here]); ?>; Your prompt response would be highly valued. Many thanks in advance. ...

Accordion content in motion

After creating an accordion, I wanted to enhance the user experience by adding a transition effect whenever they click on the accordion header. Even though I included height: auto and transition in the accordion container, it did not seem to have any impa ...

Customizing the active state of a Dropdown Item in Bootstrap version 4.5

Recently, I've embarked on the journey of creating my own theme using a combination of SASS and Bootstrap. However, I've hit a little snag when it comes to achieving the desired active appearance for a dropdown item within a navbar. To be complet ...

What is the best way to add a -webkit-transform to a div without affecting its enclosed elements?

Is there a way to apply a webkit transformation to a div without affecting the text inside? I need help with achieving this. Below is my current code: .main_div { width:200px; height:100px; background:red; margin-left:55p ...

What is the best way to extract values from promises that are still pending?

Having some issues with the code below and unable to achieve the desired output. Any help in identifying what's wrong would be greatly appreciated. Thanks! Here is the code: // Making http requests const getJSON = require('get-json'); ...