Changing the Color of a Table Cell with jQuery

I have designed a table cell in the following way

<tr>
<td id = 'even'>row 8, cell 1</td>
<td  id = 'odd'>row 8, cell 2</td>
</tr>

The colors and font sizes are defined using the CSS below

 #even {    font-size : 10pt;    color : red;    background-color:yellow; }
 #odd {    font-size : 20pt;    color : white;    background-color:green; }

Now I would like to interchange the color of even and odd cells by clicking a button

<button id='swapcolor' type="button" >Swap Colors</button>

The font size should also switch.

I have attempted to accomplish this in the following manner

$("#swapcolor").click(function (e) {

      $('table #even').css('background-color','green');
      $('table #odd').css('background-color','yellow');

});

$("#swapfont").click(function () {
      $('#even').css("font-size", "20pt");
      $('#odd').css("font-size", "10pt");
});

My issue lies in figuring out how to capture the current color of the cell

Thank you in advance for any assistance

Answer №1

It is recommended to utilize an overriding class instead of directly applying CSS through JavaScript. The provided code will switch a class for the #even and #odd table cells.

CSS

 #even {    font-size : 10pt;    color : red;    background-color:yellow; }
 #odd {    font-size : 20pt;    color : white;    background-color:green; }

 #even.swapColor {    background-green; }
 #odd.swapColor {    background-yellow; }

jQuery

$("#swapcolor").click(function (e) {
      $('table #even, table #odd').toggleClass('swapColor');
});

Answer №2

The .css() function doubles up as a retrieval tool too

let evenBgColor = $('table #even').css('background-color');
let oddBgColor = $('table #odd').css('background-color');

Answer №3

It is always recommended to use CSS classes over #IDs for styling purposes. When using jQuery, make sure to verify the presence of the .odd class on the element before replacing it with the .even class, and vice versa.

Answer №4

When you execute the code $('table #even').css('background-color'), it will display the current background color of the specified element.</p>
    </div></answer4>
<exanswer4><div class="answer" i="9901078" l="3.0" c="1332893906" m="1342915072" a="VEdI" ai="336423" e="THVrZQ==" ei="766441">
<p><code>$('table #even').css('background-color')
retrieves the present color

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 refresh a page once the 'ok' button is clicked with sweetalert

Hey there! I recently used sweetalert in my code. swal("Great work!", "You successfully clicked the button!", "success") This code triggers a message box with an 'okay' button. I am wondering if it is possible to automatically refresh the page ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

Trim the edge of a dynamic picture

Currently, I am facing a challenge with an image that requires the corner to be cut off. The image needs to be responsive in order to adjust its size according to the page dimensions. Since the image is managed by a CMS, the corner cut has to be done progr ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

Error 500 in WordPress Child Theme due to AJAX Internal Issue

I have encountered an issue with my Ajax code in the Js/Jq block (/buscador/menuLateral/menu-libros.php): $.ajax({ url: '<?= get_stylesheet_directory_uri(); ?>' + '/buscador/buscador-functions.php', type: 'POST' ...

Adding data from PHP into a designated div element

update: After some trial and error, I managed to find a solution using jQuery and append() methods. From my PHP code, I created an array containing all the necessary information that I wanted to insert into the tab divs. I then encoded this array into JSON ...

Disregard the CSS styling within the modal window

Currently, I am working with ReactJS and ANTD. My modal has been adjusted with paddings to center-align the text, but now I want to enhance the design. Here is the desired look: https://i.stack.imgur.com/qef7n.png This is how it appears at the moment: htt ...

Eliminate unnecessary spaces in the input field located below the provided text

In the html code, I have an input field that looks like this: This is the CSS for the input fields: .form-control-1 { display: block; margin: 0 auto; width: 30%; height: 50px; padding: 6px 12px; font-size: 18px; line-height: 1.42857143; c ...

When viewed on a mobile device, the page defaults to displaying the NumPad instead of the Text Keyboard in Angular

The email field in my angular app is opening a Key Pad in mobile view and I'm not sure why. <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> <div class="emailaddress" style="text-align:center;" *ngIf="!showEmail"& ...

What could be the reason for the issue with Backbone.js and modal window breaking on IE9?

I have a basic contact management table in backbone.js that utilizes twitter's bootstrap-modal to display the form input. While everything works smoothly in Firefox and Chrome, I am encountering issues with the modal not appearing in IE 9. Additional ...

Encountering a TypeError with DataTables and Tabledit

I've been attempting to integrate DataTables with Tabledit, but I keep encountering the error message "TypeError: Cannot set properties of undefined (setting 'nTf')". The number of tags also matches up. Interestingly, if I comment out the " ...

Tips for inserting values into a string array using jQuery or Angular 7

I have a series of checkboxes with values obtained from a loop. Instead of pushing these values into an array, I need to join them together as "parent1", "parent2", "parent3" and display the result in the console. Below is the code snippet for reference: ...

How to style HTML li elements to wrap like sentences within a paragraph

I am looking to format text list elements in a way that they wrap like sentences within a paragraph. Here is the accompanying HTML & CSS code snippet that demonstrates how li element behaves when it exceeds the width of the ul container. ul { ...

Achieving Text Wrapping Around Unconventional Shapes Using CSS

I'm currently facing a challenge in getting text to wrap around an irregular shape on a web page. Despite numerous attempts, I have yet to find a solution that meets my requirements. Attached is an image illustrating the layout I am aiming for. The ...

The code snippet $(this).nextAll("#...").eq(0).text("***") isn't functioning as expected

I am experiencing an issue with the following line of code: $(this).nextAll("#status").eq(0).text("Deleted"). I am trying to insert the text "Deleted" in a <span> tag, but it does not seem to be working... Here is my code: admin.php PHP: $sql = "SE ...

The blur filter in Safari causes colors to appear distorted

I am having an issue trying to add a blur filter to an SVG element. It appears that Safari is not rendering the colors correctly. Take a look at this example: <svg height="110" width="110"> <defs> <filter id="f1" x="0" y="0"&g ...

Excessive content - letter "y" disrupts the row layout on mobile devices

I have created a custom CSS class called "custom-class" and applied it to the col div. This column contains dynamic images, so I have added a vertical scrollbar property to handle the overflow. While everything looks fine on a desktop, the layout breaks o ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...