Retrieve the CSS style from a class associated with a specific element within a CSS file and apply it to another element using jQuery

My scenario is fairly straightforward. Below is the simplified CSS:

UPDATED FOR CLARITY:

#id2 .mycolor
{
color:white;                    
background-color:red;
}

#id3 .mycolor
{
color:green;                    
background-color:blue;
}

#id3:active
{
color:red;                    
background-color:white;
} 

I am looking to dynamically assign these classes to other elements using:

$('some_element').addClass(???);

Naturally, I could create a new class that mirrors the existing ones and use that name. Is there a method to reuse the class currently associated with other elements or selectors without creating a new one and without causing conflicts? For instance, how can I dynamically apply the styles in #id2 .mycolor to one element and #id3 .mycolor to another element, noting they are distinct?

Furthermore, I prefer to have the styles statically defined in the file. I do not want a JavaScript solution that extracts the current styles applied to the elements as it may differ from those specified in the external CSS file. For example, querying $('#id2').css('color') might not return "white" due to various factors.

Answer №1

Update in line with the latest requirements - To transfer css styling from one class to another, you can utilize the following code snippet,

function copyCssStyles(classA) {
    var styleSheets = document.styleSheets;
    var styles = {};
    
    for (var i in styleSheets) {
        var rules = styleSheets[i].rules || styleSheets[i].cssRules;
        
        for (var r in rules) {
            if (classA.is(rules[r].selectorText)) {
                styles = $.extend(styles, convertCssToJson(rules[r].style), convertCssToJson(classA.attr('style')));
            }
        }
    }

    return styles;
}

function convertCssToJson(css) {
    var jsonStyle = {};

    if (!css) return jsonStyle;

    if (css instanceof CSSStyleDeclaration) {
        for (var key in css) {
            if ((css[key]).toLowerCase) {
                jsonStyle[(css[key]).toLowerCase()] = (css[css[key]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");

        for (var key in css) {
            var parts = css[key].split(": ");
            jsonStyle[parts[0].toLowerCase()] = (parts[1]);
        }
    }

    return jsonStyle;
}

Pass a jQuery object into copyCssStyles() and it will return an object containing the styles, which you can then apply using jQuery's $().css(), like this:

var stylesToCopy = copyCssStyles($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(stylesToCopy);
:)

Source - Can jQuery get all CSS styles associated with an element?

Answer №2

Just follow this simple solution by using the addClass() method.

$('#element').addClass('myClass');

SEE IT IN ACTION HERE

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

What are some ways to conceal database connection details for a basic HTML/CSS/JavaScript website hosted on GitHub Pages?

For my current school project, I am utilizing vanilla HTML, CSS, and JS. Once completed, the expectation is for the repository to work through GitHub Pages. Although it's beyond the assignment requirements, I am interested in integrating a Firebase Fi ...

What is the best way to use PHP in order to retrieve the element containing the visit ID from the specific row within an HTML table?

I am working on a project that involves populating an HTML table with data from a database. The table includes an approval button for administrators to approve visits and change their status to APPROVED. I am trying to figure out how to select the element ...

Svelte components loaded with no design aspects applied

I encountered an issue while trying to integrate the "Materialify" and "Carbon Components for Svelte" libraries into my Sapper project. The components seem to be loading, but without any associated styles. I followed the installation commands provided on t ...

What is the best way to fadeTo() all elements excluding one specific div?

For my tutorial, I am looking to create a fading effect for all divs on the page except for a specific one that I want users to focus on. How can I achieve this using fadeTo? Currently, I have the code set to fade the entire body of the page. Is there a w ...

Fancybox provides a variety of effects, including those with and without scrollbars, which may vary between a server and

It's quite an odd problem I have. The effects display differently between localhost and the server, as illustrated below. Just a reminder: I'm using identical code for both environments. When uploaded to the server, the fancybox is not properly ...

The order of execution is not maintained for $.getJSON() calls within the $.each() loop

As I iterate through an HTML table, I am making a $.getJSON() request based on the data in each row. My goal is to retrieve the data from that $.getJSON call and update the corresponding row with it. Unfortunately, when I run my code, it seems to be execu ...

Avoiding line wrapping can be achieved by hiding elements using the d-none class from Bootstrap

During the development of a responsive website, I encountered an issue with the topbar menu. The menu contains numerous options, which is ideal for larger screens. However, on smaller viewports like cellphones, the buttons start wrapping rather than fittin ...

Discovering the Live Position of an Element

How can I retrieve the real-time position of a div element? I have attempted the following approach: html div id: 'square'; script: (html jQuery new draggable onStop: (html jQuery ajax callback: [Transcript show: html jQuery this ...

One handy way to navigate back to the top of the page from a .js.erb

I'm currently working on a website project utilizing Rails 3, and I encountered an issue where I needed to scroll to the top of the page after displaying an error message at the top. I attempted to achieve this by adding the following code in my disp ...

Cease execution of the jQuery function after a specific duration of time

Is there a way to modify this script on my website that displays an image from my webcam? Currently, the image refreshes every 5 seconds, but I want it to stop after 30 seconds to avoid using too much bandwidth. Any suggestions on how I can achieve this? ...

What is the best way to obscure or conceal images of runners?

I am trying to figure out how to blur or hide the runner thumbnails on different streaming sites, such as Prime Video. I typically use the Amino: Live CSS Editor chrome extension or uBlock Origin to manipulate elements on websites. However, I am struggling ...

Issue with the format of incoming data in Ajax post request when working with Django framework

Hello everyone, I am currently working on a script to send a post request to my Django backend. My goal is to have the data in Json format. <input id ="my" type="submit" onclick="me()"/> <script> function me() { var data2 =JSON.stringif ...

Take out the class attribute from the HTML tag

Despite the simplicity of this task, I find myself in a bit of a bind. I am trying to eliminate ui-mobile from my <html> tag <html class="ui-mobile"> I attempted the following approach $(html).removeClass('.ui-mobile'); However, i ...

Reset the change function after the click function has been executed

I am currently using the change event handler for my input elements and then prompting users with questions. All of my code resides within a click function. I would like to allow users to answer the questions again, without retaining their previous data. S ...

The anchor tag with an id attribute only functions properly when I select "open in a new tab."

Can anyone help me with a weird issue I'm facing? I have a div containing an anchor tag with an id, but when I click on the anchor tag, it doesn't open the link. Strangely, if I right-click and open it in a new tab, it works fine. Any idea why th ...

Identifying the method through which a simple modal window was closed, whether it be through an iframe, closeHTML, escClose, or overlayClose

My goal is to utilize simplemodal in order to showcase a form through an iframe. The form has the ability to close the modal and trigger the onClose callback function which refreshes the main screen, updating the displayed information. However, I am lookin ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

When the direction is right-to-left (rtl), the floating labels in Bootstrap slide towards the center

Seeking to implement floating labels in Hebrew using bootstrap v5.2, I encountered a challenge. When switching the direction to rtl and clicking on the input box, the label slides towards the center. Here is my code snippet: <div class="form-f ...

Secure your accounts with our innovative password manager tool that allows you to easily create, manage

Is there a way to show text in dots format using HTML, similar to how it appears in a password field, like this: Password: <input type="password" name="pwd">This text looks like dots</input> Without relying on an <input>? I'm inter ...