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

Changing the border color of a Material UI textbox is overriding the default style

Upon the initial page load, I expected the border color of the text box to be red. However, it appeared grey instead. I tried setting the border color to red for all classes but the issue persisted. Even after making changes, the border color remained unch ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Checking for null values using the "and/or" syntax

While reading an article on special events in jQuery, I came across a syntax that was unfamiliar to me: var threshold = data && data.threshold || 1 I have previously encountered the following: var threshold = data.threshold || 1 As far as I kno ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

highcharts-ng expands in flexbox without contracting

I've encountered an issue while trying to incorporate a highchart within a flexbox container. The chart expands along with the container without any problems, but it fails to contract when the container size decreases. My current setup involves angul ...

The ajax request is unsuccessful due to the inability to convert text to string

After upgrading my page from using jquery 1.4.4 to jquery 1.9.1, I encountered an issue where my ajax calls stopped working. Reverting back to jquery 1.4.4 resolved the problem. The error message received was: No conversion from text to string Here is ...

Tips for applying a CSS wrapper to an element, not just text

I am working with a group of span elements within a td that has a set width. My goal is to wrap the span elements onto new lines without breaking up the text inside them. For example, if I have: <td> <span>bind</span> <span&g ...

The inlineNav edit button is experiencing errors when used in conjunction with the multiselect feature in

My multiselect inline editable jqGrid with inlineNav is encountering some issues. The problem arises when following these steps: Click on the add button to display an empty record in the grid, add data, and save it. Select that record using the checkbox. ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

JavaScript unable to access elements during page loading

I am facing an issue with the following code: var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); v ...

Uploading files with jQuery AJAX across different domains

What I'm facing is an issue with uploading files to a subdomain that serves as an API endpoint for file uploads. Every time I try to upload a file using jQuery from the main www domain to this subdomain, I encounter an error. XMLHttpRequest cannot ...

What is the best way to access all of a class's properties in JavaScript?

Is there a way to retrieve all the properties of a class using JavaScript? For example, if I have a class like this: .menu { color: black; width: 10px; } How can I extract "color: black; width: 10px;" as a string using JavaScript? Thanks in advance! ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

I can't seem to figure out the source of this unexpected padding/margin on my website

After creating a website for a church using Foundation, SASS, and Compass, I noticed a horizontal scroll issue when resizing the window. Adding overflow-x: hidden; seemed to fix it, but there was still about 20px of padding on the right side when testing ...

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

"Text data will be automatically cut at the end of a page and continue

I encountered the following issue As depicted in the image The data is not being displayed properly In the next td, the last character 3 is also printed on the next line Is it possible to avoid page footer and header without adjusting the page margin? ...