Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td cell.

The desired outcome is to transform the following: https://jsfiddle.net/cyztevwx/ into https://jsfiddle.net/4ocj14rq/1/

Original HTML Structure

<table style="width:100%">
    <tr>
        <td class="test1" style=""><div style="background-color:#63BE7B;">227.96</div></td>
        <td class="test2" style=""><div style="background-color:#F8696B;">227.96</div></td>
        <td class="test" style=""><div style="color:blue;">227.96</div></td>
        <td class="test1" style="">227.96</td>
        <td class="test1" style="color:white;"><div style="background-color:#F8696B;">227.96</div></td>
    </tr>
</table>
<button type="button" id="size">Change font size</button>

Modified HTML Structure

<table style="width:100%">
    <tr>
        <td class="test1" style="background-color:#63BE7B;"><div style="background-color:#63BE7B;">227.96</div></td>
        <td class="test2" style="background-color:#F8696B;"><div style="background-color:#F8696B;">227.96</div></td>
        <td class="test" style=""><div style="color:blue;">227.96</div></td>
        <td class="test1" style="">227.96</td>
        <td class="test1" style="color:white;background-color:#F8696B;"><div style="background-color:#F8696B;">227.96</div></td>
    </tr>
</table>
<button type="button" id="size">Change font size</button>

As can be observed, certain td cells already possess a style attribute, while others are empty. Some td cells contain div elements and some do not, additionally, some td cells have styles but lack background color specifications.

Answer №1

In order to achieve this particular task, you can use the following code:

$(window).on('load', function() {
    $('td.column').each(function() {
        var background = $(this).find('.box').css('background-color');
        if (background !== 'rgba(0, 0, 0, 0)') {
            $(this).css('background-color', background);
        }
    });
});

This code will iterate through each td element that has a class of "column". It will then retrieve the background color value from the child div with a class of "box". If the background color is not transparent, it will apply that color to the parent td element.

If you want to ensure that no transparent values are used at all, you can add an additional condition like so:

$(window).on('load', function() {
    $('td.column').each(function() {
        var background = $(this).find('.box').css('background-color');
        if (background !== 'rgba(0, 0, 0, 0)' && background !== 'transparent') {
            $(this).css('background-color', background);
        }
    });
});

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

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

What could be causing the submission failure of the form post validation?

My Code: <form method="post" name="contact" id="frmContact" action="smail.php"> ... <label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3>& ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Steps to center an HTML canvas on the screen

I attempted to center my canvas horizontally using <div style="text-align:center;">, but the y axis remains unchanged. How can I position the HTML canvas in the center of both the x and y axes? Any suggestions on how to achieve this alignm ...

AngularJS 1.7.x's ngRoute tabs navigation post authentication

In my current project, I am using ngRoute to route users to the login page and upon successful login, they should land on the dashboard page. However, I am facing a problem with the dashboard page where I need to have two or more tabs that render HTML pag ...

Text centered over an animated underline using CSS

Seeking help with my bootstrap 4 nav menu. I have implemented a CSS animation that creates an outward underline effect for the nav-link items. However, I am struggling to center the text above the line. Any suggestions on how to achieve this? I attempted ...

The specified 'image' identifier has not been defined. There is no such member within 'never'

Edit :: Finally, I managed to get the output successfully, but there's still an error that baffles me. https://i.stack.imgur.com/2wrNM.pngAlthough I've tackled similar issues in the past, this particular one seems elusive. I attempted using "?", ...

Using the Twit package on the client side: a step-by-step guide

I have been utilizing the Twit package for searching tweets. After executing the js file in the console, I am able to see the tweets but when trying to use them on my webpage, an error 'Uncaught ReferenceError: require is not defined' pops up. Th ...

Step-by-step guide on redirecting a page from a Django form

I'm in the process of developing a dictionary application that allows users to input a word through a form. The issue I'm facing is that when a user enters a word and hits submit, the form disappears leaving only the submit button and the search ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

In need of clarification on the topic of promises and async/await

I have been utilizing Promises and async/await in my code, and it seems like they are quite similar. Typically, I would wrap my promise and return it as needed. function someFetchThatTakesTime(){ // Converting the request into a Promise. return new ...

Unable to perform filtering on a nested array object within a computed property using Vue while displaying data in a table

Lately, I've been experimenting with different methods to filter data in my project. I've tried using various approaches like methods and watchers, but haven't quite achieved the desired outcome yet. Essentially, what I'm aiming for is ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

Having trouble loading xml/xsl files on IE11? Consider enabling compatibility mode to ensure smooth rendering on your xml/xsl page

On my website, I have a page that displays XML from an XSL document. Strangely, it works perfectly on IE8 but not on IE11 - the page appears blank even though the XML is present when viewing the source. Interestingly, if I enable compatibility mode for the ...

After all other content has been fully loaded, jQuery UI is then loaded onto

For a while now, I've been following a YouTuber's JQuery UI tutorial. Every time I refresh the page, my HTML loads first and then my CSS fills in, causing a momentary flash of HTML and CSS without the UI. Is this normal? Can it be prevented? Her ...

Internet Explorer does not support the split function in JavaScript

I've been utilizing the split function to separate dates, but I encountered an issue where the code doesn't function properly in Internet Explorer, although it works fine in other browsers. The ul and li elements are dynamically generated. <! ...

What is the best way to position a website in the center in the provided example?

Simple question here, couldn't find it in the search so sorry if it's a repeat. How is the content on this responsive website centered? I've checked the body margins but can't seem to locate anything. Thank you for your help. ...