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

Browsing the website through http://localhost instead of file:// while utilizing node.js

I am currently in the process of familiarizing myself with node.js. Everything appears to be running smoothly when I access the site from file:///C:/.../myfolder/index.html. The jquery and bootstrap files are located in the directories myfolder/css/ and m ...

Tips for customizing the appearance of the Alert Dialog in React-admin?

React-admin alert dialog example I'm currently working on a React-admin project and I am looking to customize the alert dialog that displays errors, warnings, and success messages on the page. Specifically, I want to apply CSS styles like z-index and ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

What is the best way to iterate through this JSON data and add it to a div in an HTML document?

Here is the structure of my JSON: { "content": [ { "title": "'I need some rest'", "description": "Descript One", "link": "http://www.google.com/?id=90#hhjjhjC-RSS", "guid": "http://www.google ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

What is the process for customizing the color and thickness of the active tab inkBarStyle in React Material-UI?

Check out this inquiry: How can I change the color of the active tab in MUI? And for a potential solution, have a look at this response: The provided answer seems to be effective: <Tabs inkBarStyle={{background: 'blue'}}>... However, I a ...

rendering google charts using jade template

I am facing an issue while trying to display a google annotated chart on my jade project. I managed to successfully load a pie chart, but I am having trouble rendering a chart that requires the container element size to be explicitly defined. You can find ...

Develop adaptable flex items

I am working with a container element that contains variable child elements whose width I want to scale. To see an example of what I'm trying to achieve, take a look at this simple plunker: https://plnkr.co/edit/ef0AGPsK7FJJyBqgWuMi?p=preview When ...

Designing a fluid dropdown menu with scroll functionality for my website

I have been trying to implement a scrollable dropdown menu on my website by following various tutorials, but none of them seem to be working. Despite my efforts, the dropdown menu remains non-scrollable. HTML <li> <a href="#">Team ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

Steps for Building and Exporting a Next.js Project Without Minification and Optimization

Is there a way to build and export a Next.js project without minifying and optimizing the output files? ...

React encountered an unexpected termination of JSON input during parsing

Upon running npm install, I encountered an error that is shown in the following link: https://i.stack.imgur.com/nVvps.jpg This issue has been causing trouble for me today and I'm unsure of the reason behind it. ...

Having trouble executing the yarn command for clasp login

Issue with running yarn clasp login I am not very proficient in English, so please bear with me. 8> yarn clasp login yarn run v1.22.22 $ C:\Users\myname\Desktop\個人開発プロジェクト\clasp-240418\node_modu ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

What could be causing my ajax not to retrieve the text currently being typed in the input form?

I am facing an issue with my form where I am unable to update the data when typing something new into the input field. It seems like the form is not picking up the currently typed string when on the update page, and instead it's using the echoed out v ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

A versatile multi-select jQuery widget featuring the ability to choose options within a specific opt

I am on the hunt for a cool jQuery tool that has the following characteristics: It enables you to create multiple groups, such as: Group 1 - Sub 1 1 - Sub 1 2 - Sub 1 3 Group 2 - Sub 2 1 Group 3 - Sub 3 1 - Sub 3 2 By clicking on Group 1, for instance, ...

The functionality of the dropdown onchange action is hindered when creating dynamic forms

Issue I have a dynamic form that gets generated when a button is clicked. In this form, there is an invoice dropdown menu where the selected invoice amount should be displayed in the adjacent text box using AJAX. However, I am facing an issue with the cha ...