Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function:

$(document).ready(function()
{
    // create 9:00 and 9:30 cells for both employees
    generateAvailabilityGrid($("#oneDay"), 30, 9, 10);
});


/* NOTE: This function works as expected. I have tested it */
// function that generates the availability grid for availabilitySchedule
// parameters: ID of container to write availability grid to (or index), size of interval block (in minutes, as integer), (optional) start time, (optional) end time
function generateAvailabilityGrid(identifier, intervalSize, floatStartTime, floatEndTime)
{
    // for good measure, define floatStartTime,floatEndTime as 9 AM,9 PM, respectively
    floatStartTime = floatStartTime || 9;
    floatEndTime = floatEndTime || 21;
    // enforce intervalSize to be greater than 10
    if (intervalSize < 10) return;
    // enforce floatSize,floatEndTime to be between 0 and 23.99
    if (((floatStartTime < 0) || (floatStartTime >= 24)) || ((floatEndTime <= 0) || (floatEndTime >= 24))) return;
    // create container div element (will serve as availabilityTable)
    var tableDiv = $('<<div class="table"></div>>');
    // create dummy row div, dummy cell div
    var dummyRowDiv = $('<div class="tableRow"></div>'),
        dummyCellDiv = $('<div class="tableCell"></div>');
    // get names from #employeeTable
    var names = $('#employeeTable tr:not(#titleRow)').map(function() { return $(this).children(':lt(2)').map(function() { return $(this).children('input').val(); }).get().join(" "); });
    // for every name in names
    $(names).each(
        function()
        {
            // copy dummy row and append label with name to it
            var row = $(dummyRowDiv).clone();
            row.append($("<label></label>").text(this));
            for (var m = floatStartTime * 60; m < floatEndTime * 60; m += intervalSize)
            {
                // create cells
                var tempCell = $(dummyCellDiv).clone();
                if ((m % 60 == 0) && (m > floatStartTime))
                {
                    $(tempCell).addClass('hourMark');
                }
                // have cell, on click, be marked 'available'
                $(tempCell).click(function() { $(this).toggleClass('available'); });
                // TODO: fetch data and use it to "fill" appropriate cells
                // append cells to row
                $(row).append(tempCell);
            }
            // append row to container div
            $(tableDiv).append(row);
        });
    // determine if identifier is int
    var isIntIdentifier = (identifier > -1);
    // append tableDiv to div identified by identifier
    // if identifier is int
    if (isIntIdentifier)
    {
        // use index to get container to append tableDiv to and append
        $('#availabilitySchedule :nth-child(' + (identifier + 1) + ')').append(tableDiv);
    }
    else
    {
        // get container to append tableDiv to by name and append
        $(identifier).append(tableDiv);
    }
}

The CSS rules that are being targeted but not taking effect are:

.hourMark
{
    border-right: 2px solid #000;
}

.available
{
    background: #0f0;
}

It appears that the issue may lie in attempting to add classes and mouse click listeners to temporary objects within the for-loop. Here is a minimal reproducible example of the problem: https://jsfiddle.net/b73fo0z5/

Does this mean that I will need to define everything outside the for-loop, after the cells have been added to the table div? If so, can you explain why?

Answer №1

The problem arises from the hierarchy of CSS rules being determined by selector specificity.

Simply using classes may not provide enough specificity to override the default background rule. This can be confirmed by inspecting elements in the browser's dev tools and viewing the applied rules in order of their specificity.

You can try this:

#availabilitySchedule .available
{
    background: red;
}

For more information, check out this helpful article https://css-tricks.com/specifics-on-css-specificity/

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

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

"Enhance Your Website with Dual Functionality Using JQuery's One

I am trying to run two functions on a click event. Each function works fine on its own. However, I am encountering an issue when I execute functionA followed by functionB. The problem seems to be originating from functionB. I suspect it is because of the ...

What is the best way to save newly added elements on a webpage that were submitted by the

I am looking for a way to save the changes made by users on my webpage so that they can navigate to different pages and come back without losing any added elements. These changes should be retained even when the user goes back to edit the webpage, but I pr ...

Take out property that was placed in the "style" tag

One particular static HTML file that I have consists of the following code: <style> p { overflow-wrap: break-word; word-break: break-word; hyphens: auto; } </style> <div id="wrapper"> <p>Insert text here ...

Unable to export Interface in Typescript - the specific module does not offer an export named Settings

I am encountering an issue while trying to export/import an interface in Typescript. The error message I receive is causing confusion as I'm unsure of where I went wrong. Uncaught SyntaxError: The requested module '/src/types/settings.ts' ...

Switching React components with const

Having some difficulties with the React Switch feature. Attempting to create a layout within another layout, and so far, everything seems to be functioning correctly. import React from "react"; import {Redirect, Route, Switch} from "react-router-dom"; imp ...

Guide on generating a dynamic loop in JavaScript using the group name as a variable

I have been attempting to organize a group, dynamically ungroup it, and then create a loop with each element of the group. Despite reviewing multiple examples, I have not been able to solve the following issue: The grouping is done based on the "tipo" pro ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

Error: Null value detected while trying to access the property 'appendChild'

Can anyone help me with this error? Uncaught TypeError: Cannot read property 'appendChild' of null myRequest.onreadystatechange @ script.js:20 Here's the code snippet where I'm facing the issue // index.html <html> <he ...

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Transform JavaScript code into HTML using jQuery.`

I have a piece of HTML and JavaScript code. The JavaScript code is currently in jQuery, but I want to convert it to vanilla JavaScript: // Vanilla JavaScript code document.querySelectorAll('.hello[type="checkbox"]').forEach(item => { item ...

Displaying multiple arrays using ng-repeat

My task is to display a list organized by date, but the problem is that the list is not sorted and I can't figure out when the date changes. This situation is similar to having the following Json: list = {name: first, date: 2014-05-21}, { {name: sec ...

What is the method for styling the third list item in a CSS hierarchy?

I'm struggling to understand the hierarchy in CSS for creating this specific layout. I've searched for explanations, but haven't found a clear one that breaks down how each level works. This is my first time working with CSS so it's bee ...

Press the toggle button to switch the image display

Currently learning HTML and attempting to design a dashboard. I want to display the status (ON, OFF, OPEN, or CLOSED) of a room or door using an icon. I have images for open/close doors and lightbulbs. Need assistance in adding an element to all the exist ...

Error: NextJS cannot access the 'map' property of an undefined object

Hey everyone, I usually don't ask for help here but I'm really struggling with this piece of code. I've tried looking at various resources online but can't seem to figure out why it's not working. Any guidance would be greatly appr ...

What is the process for adding color to HTML elements?

Is there a way to assign unique random colors to each individual p tag in ReactJS? function App() { return ( <div> <p style={{ color: "#7fbd73" }}>Hi</p> <p style={{ color: "#3a82e4" }}>Hello</p> < ...

Maintain the menu item color even after clicking

Here is the menu code snippet: <div class="header"> <div id="logo"></div> <ul class="menu"> <li><a href="/index.aspx">Home</a></li> <li><a href="/about.aspx"& ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

Sending a parameter value from a blade view in Laravel to a controller: tips and tricks

What is the best way to pass the value "{{$ item-> id}}" to a method in a controller? For example, if we have show.blade.php with the value: "{{$ item-> id}}" In MyController.php, how can we utilize this value within the method: public function ...