Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits.
The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled day is represented by a blue square using CSS, while a partial day has a triangular shape indicating morning or afternoon (also CSS).
The issue: There's an overlapping problem between morning and afternoon segments.
Here's what I've done so far: http://jsfiddle.net/9hnNk/1

Could someone pinpoint where I might be going wrong with my jQuery selectors/replacements?
HTML:

<table>
<tbody>
    <tr>
        <td>
            morning:<br/>
            <div class="morning"></div>
        </td>
        <td>
            afternoon:<br/>
            <div class="afternoon"></div>
        </td>
        <td>
            split day:<br/>
            <div class="morning"></div>
            <div class="afternoon"></div>
        </td>
    </tr>
</tbody>


CSS:

.morning{width:0;height:0;border-bottom:60px solid transparent;border-left:94px solid #0066CC;font-size:0;line-height:0;}
.afternoon{width: 0; height: 0;border-bottom: 1px solid transparent;border-top: 59px solid transparent;border-right: 95px solid #0066CC;font-size: 0;line-height: 0;}
.fullDay{border:30px;border-color:#0066CC;border-style:solid;height:0;width:32px;float:left;color:#FFFFFF;margin-left:2px;}
.splitDay{line-height:0%;width:0px;border-top:60px outset #0066CC;border-right: 100px dashed #0066CC;}


Javascript:

jQuery(document).ready(function ($) {
if ($("td:has(div.afternoon):has(div.morning)")){
    $(".morning").addClass('splitDay').removeClass('morning');
    $(".afternoon").remove();
    }

});

Answer №1

The issue with your jQuery code is that you are creating new selectors for `$(".morning")` and `$(".afternoon")`, which will search through the entire HTML document for divs with those classes. To target the correct elements, it would be better to save your initial selector and use `.find()` on it later like this:

jQuery(document).ready(function ($) {
    var $splitdays = $("td:has(div.afternoon):has(div.morning)");
    if ($splitdays) {
        $splitdays.find(".morning").addClass('splitDay').removeClass('morning');
        $splitdays.find(".afternoon").remove();
    }
});

Answer №2

Indeed, you're on the right track by checking for the existence of the case. However, it's important to ensure that you are only manipulating the rows that match your specific case. One way to do this is by assigning the case elements to a variable and then manipulating only that variable. This allows you to modify only the split day elements without affecting other elements on the page.

jQuery(document).ready(function ($) {
if ($("td:has(div.afternoon):has(div.morning)")){
    var splitday = $("td:has(div.afternoon):has(div.morning)");

    splitday.find(".morning").addClass('splitDay').removeClass('morning');
    splitday.find(".afternoon").remove();
    }
});

For an example, visit:

http://jsfiddle.net/9hnNk/4/

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

Ways to eliminate the border color from bootstrap multiselect

I have been attempting to eliminate the border color surrounding options in a select box from Bootstrap Multiselect. Unfortunately, I am unable to identify the specific class responsible for adding the blue color around the option borders. This border app ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

Executing PHP code upon clicking an HTML button

I am currently in the process of creating a simple webpage that will execute a stress test and mimic a load on my web server. The PHP code for stress is functioning properly, however, when I attempt to click the button, nothing seems to happen. <?php ...

Troublesome CSS Zoom causing issues with jQuery scrollTop

As I design a website that has a fixed width and zooms out on mobile browsers, I've opted to adjust the zoom using CSS rather than viewport meta tags: html, body { zoom: 0.8; } It's been effective so far, but now I'm facing an issue wi ...

Is there a specific measurement or scale for the dragging feature in jQuery UI draggables?

I'm interested in adjusting the position of my draggable element based on the distance moved by the mouse. For instance, if the scale is 1:2 and the cursor is moved 10px to the right, then the draggable should move 20px. I already have my draggable ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

`I am facing difficulty in displaying a YouTube video using mediaelement.js`

I have attempted to utilize the code from the demo on the mediaelement website in order to play a YouTube video, but unfortunately, I haven't had any success! However, I have successfully played both audio and video files using the software before, an ...

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

Saving a form with repeater fields using Ajax

I created a dynamic form in HTML that allows users to add multiple members as needed. The member details are stored within a div like this: <div class="form-group form-group-100 clearfix"> <label>Name:</label> <input type="te ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Error in Next.js 13 due to Prisma table mapping causing hydration issues

I recently created a basic project in Next.js 13 and encountered a Hydration Error even though my project is not doing much. The code snippet below seems to be the cause of the issue: import { PrismaClient } from "@prisma/client"; export default ...

What steps can be taken to modify the style of a single button belonging to a broader group of elements?

Is there a way to hide the save button within a Vue Modal without affecting other buttons with the same class? .btn.btn-primary { display: none; } Simply targeting .btn-primary in the CSS affects all elements with that class, and adding .modal woul ...

Can someone assist me with positioning an HTML child element to appear behind a parent element using CSS?

I need help displaying an HTML element behind a fixed header in my webpage. I want the div element (which is a child of the header) to appear beneath the header like a dropdown menu. However, I've tried adjusting the z-index and position properties wi ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Tips for zooming to the middle of a div element

I'm trying to figure out how to create a zoom in effect on my large div, but I haven't been successful despite searching through many resources. My goal is to zoom into the center of the user's screen rather than just at a set position. ht ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...