What is the best way to transfer the style of one class to another, while also applying it to all elements in

I am looking to apply a specific style property to all child elements between the "day-start" and "day-end" classes.

https://i.sstatic.net/FS6vf.png

I attempted using code similar to this:

document.querySelectorAll('.day').forEach(
el => el.querySelectorAll('div').forEach(
el => el.style.color = 'red'
)
);

However, I am unsure on how to target elements specifically between these two classes.

Using jQuery with:

 $(".day-start").nextUntil(".day-end").addClass("foo");

successfully adds the class to the correct element but encounters issues with table row tags and does not include the .day-start and .day-end classes.

Is there a way to add the class to all content with a background color applied as an alternative solution?

Answer №1

To streamline the process, you can create a selector for all the days, iterate through them, and apply a specific class when reaching the .day-start element and remove it when reaching the .day-end element.

For example:

let isActive = false;

document.querySelectorAll('.day').forEach((day) => {
    if(day.classList.contains("day-start")) {
        isActive = true;
    }
    if(isActive) {
        day.classList.add("active-day");
    }
    if(day.classList.contains("day-end")) {
        isActive = false;
    }
});

You can view a demonstration of this concept here: https://codepen.io/bj-rn-nyborg/pen/OJRJwEN

Answer №2

To properly keep track of elements in between, consider utilizing the following approach:

let section = 0; // Our marker: 0 - pre, 1 - mid, 2 - post

document.querySelectorAll('.day').forEach(
    el => {
        if (section === 0 && el.classList.contains('day-start')) {
            section = 1;
        } else if (section === 1 && el.classList.contains('day-end')) {
            section = 2;
            // In a loop scenario, a simple `break;` would suffice
            // Unfortunately, `forEach` lacks this feature.
        }

        if (section === 1) { // Apply operations only within section 1
            el.querySelectorAll('div').forEach(
                div => div.style.color = 'red'
            )
        }
     }
);

A loop implementation provides a more straightforward solution:

let isBefore = true;

for (const el of document.querySelectorAll('.day')) {
    if (isBefore && el.classList.contains('day-start')) {
        isBefore = false;
    } else if (el.classList.contains('day-end')) {
        break; // Terminate iteration at this point
    }

    if (isBefore) continue; // Proceed to the next element after current round ends

    el.querySelectorAll('div').forEach(
        div => div.style.color = 'red'
    );
 }

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

Exclude the parent background in the child class when inheriting other properties

I need the child class to inherit all properties from its parent, except for the background color. The immediate parent has a white background, but I want the child to skip this and take the background color from the grandparent component, which is bluebac ...

Send the function with parameters, but do not pass its output

Within my component, there is a need property that holds a static function. This function is executed by middleware to handle asynchronous API calls before rendering the component. Here's an example: static need = [ myFunc(token) ] The issue arise ...

Using jQuery to animate a div when clicked by the mouse

Here's the scenario: I have 3 block elements arranged in a specific order: Image Hidden Text Block (.hidden) Footer Block (.blockimage) When the page loads, the image is displayed over the hidden text block (which contains further infor ...

The issue of PHP not being executed when using HTML AJAX

I am completely new to using AJAX, jQuery, and PHP. I am currently working on a project where the user can submit their daily weight which is then stored in a database and later displayed with graphs. My issue is that when the user submits the form with t ...

Using ISO-8601 format to display dates in JSON within a .NET WebService

While working with a .net asmx webservice, I encountered an issue with the date format being returned. The date field is in the form of: "effective_date":"\/Date(978411600000)\/" After researching on Stack Overflow here: How do I format a Micros ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

Tips for perfectly aligning an "inline-block" element with an ordered list (ol)

I'm experiencing an issue with the alignment of my ordered list. My list is structured as follows: <ol type="a"> <li><button style="display: inline-block">TEXT1</button></li> <li><button style="display: inli ...

Determine the specific Flow.js / ng-flow input (flow-btn) that was utilized for the file upload

I have several flow-btn elements scattered throughout my webpage. Users can either upload individual files directly to a list of items or choose to upload multiple files that will automatically populate the list. This functionality is contained within a fl ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

Mastering the art of nesting loops and conditions in React: A comprehensive guide

I am fetching data in React using the following method: const data = [ { header: 'my header1', copy: [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Etiam et risus quam. Pr ...

Issues with retrieving the scope attribute within a directive

I am currently facing an issue where I am unable to access the values stored in $scope.photoRes within my directive. When I use console.log(scope.photoRes) in the directive, it only displays an empty object. Here is the output from the console: Object {fi ...

Troubleshooting: Route guard in Angular 4 not functioning properly on initial page load

While using the canDeactivate guard, I attempted to prevent the browser back action. Interestingly, navigating to the site URL on a new tab successfully brings me to the initial page. However, without any user interaction on the page, pressing the browser ...

Searching and replacing several elements in JavaScript code

Seeking assistance with another query related to JavaScript. I am in need of a JavaScript function that can locate and replace multiple elements within a string. For instance: every occurrence of "identifier" should be substituted with "ID" and each insta ...

What is the best way to send all the form values as an array and iterate through them when submitting to a SQL database?

I need help with a PHP form that I want to submit the values from to a database. Since I am new to PHP, I am not sure how to save all the form values into an array and then submit them. Below is my table enclosed in a form: <form action="<?php echo ...

How can I modify the navbar-collapse in Bootstrap to alter the background color of the entire navbar when it is shown or open on a mobile screen?

Can anyone tell me how to change the background color of the navbar when the navbar-collapse is displayed? I want one background color when the navbar-collapse is shown and a different color when it's collapsed. Is there a way to achieve this using C ...

Utilizing Angular to Embed SVG Child Components Within Parent SVG Component

Main Component Template: <svg #mainSvg width="1000" height="600"> <app-custom-component></app-custom-component> </svg> Custom Component Template: <svg:image *ngFor="let img of images"></sv ...

Find the total sum of various spans

As a beginner in programming, I am facing a challenge that I cannot seem to solve. How can I retrieve the values of multiple spans with the same class? This is how the HTML code looks: <ul> <li> <input type="checkbox" value="30 ...

A convenient Delete Modal Component in React utilizing Reactstrap

I am currently working on implementing a reusable Delete Component using reactstrap, which can be called from other components. Below is the code for my DeleteModal: class DeleteModal extends Component { constructor(props) { super(props); this. ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...