Utilize specific CSS attributes from a class and apply them to a DOM element

It's clear that the question at hand is more complex than it initially appears. I'm not just looking for a way to apply a CSS class to a DOM element, as I'm already familiar with that (

<div class="MyCssCLass"></div>
)

My goal is to apply specific parts of the CSS attributes from a class to a DOM element.

Let's say I have the following CSS:

.MyClass
{
    background-color:red;
    color:blue;
}

and this HTML

<div id="MyDiv">Some text</div>

If I want to only apply the background-color to MyDiv, I can't simply do:

<div id="MyDiv" class="MyClass">Some text</div>

Because this will also apply the CSS color attribute to MyDiv, which is not the desired outcome.

At this point, you may be wondering why not just override the CSS class with my own CSS or create another class like MyBckgrdClr with just background-color:red; and assign it to MyDiv?

However, life is not always that simple.

With my understanding, I attempted a solution using JQuery:

I dynamically created another <div> and assigned it the MyClass CSS class.

var MyClassElement = $('<div id="MyClassElement">').addClass('MyClass');

Then I inserted it into the body

$('body').append(MyClassElement);

Next, I tried to change the background of MyDiv

$("#MyDiv").css("background", MyClassElement.css("background"));

While this worked well in Chrome, it did not function properly in Mozilla, IE, Opera...

But fear not! I still have some tricks up my sleeve. Let's explore another approach!

What if I try a JavaScript solution?

My initial thought led me to this line of code:

document.getElementById('MyDiv').style.background = document.getElementById('MyClassElement').style.background;

Unfortunately, this did not work as expected. Even Chrome failed to display the background properly...

So, what should I do now...

... ...

Hmm...

... ... ... ...

Ah! I remember now! I'll resort to a method not commonly used these days. Ah yes, debugging.

Let's see what

document.getElementById('MyClassElement').style.background
returns

So I added:

console.log(document.getElementById('MyClassElement').style.background);

right after the

$('body').append(MyClassElement);
line and checked the console for the output:

(an empty string)

...

It seems my wisdom is diminishing rapidly.

Is there someone wiser than me who can point out my error and provide a solution to achieve this?

Specifically, I would like to understand

Why did the JQuery solution work in Chrome but not in other browsers? And why did JavaScript fail across all browsers?

Fiddle: jsfiddle.net/7h2Lsxmx/3/

P.S. I also noticed that CSS attributes in .MyClass do not seem to affect any of the .style attributes of a JavaScript DOM Element, nor do they work with .css() for the JQuery counterpart.

EDIT:

Here is some additional context.

I have 5 CSS files.

dark.css, light.css, gray.css, blueish.css, kindOfGreen.css

They all contain the same classes but with different values for each attribute.

For example, dark.css may include:

.MyClass
{
    background-color:black;
    color:gray;
}

and Blueish.css may have:

.MyClass
{
    background-color:(Put rgb for dark blue here);
    color:blue;
}

By switching between these CSS files at runtime using PHP, I can change the color scheme of my page.

Thus, the goal is to:

1- Allow the user to choose a theme 2- Store the theme choice in a cookie 3- Reload the page with the appropriate CSS file

Given this dynamic nature, I cannot (@Matthias I won't) manually code a class for every property that changes in each of the five CSS files. If I can make the code work in at least Mozilla and IE without altering the class (which is used on other elements too), that would be ideal.

Answer №1

style provides access to an element's inline style only. For full access to all styling properties, utilize getComputedStyles. Learn more about this in-depth with examples by visiting this link.

Answer №2

.green-text-color { 
  color: green;
}

.yellow-background {
  background-color: yellow;
}

<div class="green-text-color">This div has green text color</div>

<div class="yellow-background">This div has a yellow background</div>

<div class="green-text-color yellow-background">This div has a green text color AND yellow background</div>

It's puzzling why this content is presented in this format.

Answer №3

Did you know that it's possible to assign multiple classes to a single element? Simply separate them with a space, allowing you to create more specific selectors.

If that doesn't work, you can always create a new selector, like one that specifically targets div elements with the class "div.MyClass".

Personally, I find using JavaScript for this task to be less than ideal.

Answer №4

Have you ever wondered when it might not be possible to include additional CSS classes?

In any case, you can always override CSS by using the 'important' property.

JavaScript:

$("#MyClass").css('color','black','important');

View the code in action on jsFiddle: http://jsfiddle.net/7h2Lsxmx/1/

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 is the functionality behind a free hosting website?

Is anyone familiar with websites like Hostinghood, where users can create a subdomain and upload HTML, CSS, etc.? I'm curious about how they operate and how I can create a similar site. This is my first question here, so please respond instead of disl ...

Engage with Vue.js and traditional JavaScript (plain) in your projects

Exploring the integration of Vue with regular JavaScript has presented a challenge. While some solutions online propose moving all functions to a Vue component, this approach proves impractical for complex or large functions. The task now is finding a way ...

Mysterious area located within a flexbox set to display items in a column arrangement

There is a mysterious gap within a flexbox that has a column direction. In the header-left div, I have set up a flexbox with a column direction. It consists of three nested divs: left_text_heading, hero-img, and hero-text. Strangely, there is an unknown s ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Current recommended method for updating innerHTML with properly formatted text?

My understanding is that using innerHTML on an element can be risky, as malicious users could potentially inject harmful content such as <script> tags. This question shows there are multiple alternative tags, some of which are non-standard. In my s ...

"When running next build, NextJS fetch() function throws an error indicating an invalid URL, but everything works fine when using

Currently, I am in the process of developing a NextJS React application and attempting to retrieve data from my server by using the following line of code: let data = await fetch('/api/getAllAlumniInfoList').then(res => res.json()) Interestin ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

tips for arranging the body of a card deck

I have a card-deck setup that looks like this https://i.sstatic.net/vuzlX.png I am trying to arrange these boxes in such a way that the total width of the box equals the sum of the Amazon Cost width and the BOXI+ width: https://i.sstatic.net/3uNbe.png He ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...

Rendering a Component Inside Another Component

I am facing a situation where I have a component named TicketView being used within another component called Table. The initialization of TicketView in the table looks like this: <TableRow key={index}> ... <TableRowColumn style={{width: & ...

Styling the Container Component in ReactJS

I need to apply some styling to the "Forms_formline__3DRaL" div (shown below). This div is generated by a component, but it seems that the style I want to add is being applied to the input instead of its parent div. How can I use ReactJS to set the style " ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

How do I retrieve the value of a class that is repeated multiple times?

In the HTML code I am working with, there are values structured like this: <div class="item" onClick="getcoordinates()"> <div class="coordinate"> 0.1, 0.3 </div> </div> <div class="item" onClick="getcoordinates() ...

Utilize flexbox for text wrapping while preserving the proportionate column width for varying text lengths

I'm currently working on a Wordpress site, incorporating flexbox into my design. I have set up two columns where child 1 should occupy 75% of the page width and child 2 should take up 25%. However, I've noticed that when the content in child 1 is ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

R code for extracting data without using CSS path

Hey there, I'm reaching out because I'm struggling to figure out how to extract data from a webpage (""). Learning how to scrape data is my current project, and I'm specifically trying to gather contact information (Office, Fax, email) from ...

The error message "global.HermesInternal - Property 'HermesInternal' is not found in the type 'Global & typeof globalThis'" appeared

I ran the auto-generated code below: $ react-native init RepeatAloud App.tsx /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local * ...

A runtime error occurred in ScriptResource.axd at line var f = ($telerik.isIE) ? document.createElement('<iframe name="' + this.get_id() + '">');

I am encountering an error during runtime in the ScriptResource.axd file, which is causing a major issue for me as I am unable to modify the code directly to fix it. The error seems to be specific to this line: ScriptResource.axd runtime error on line var ...

Plugin for jQuery that paginates text when it overflows

Looking for a solution here. I have a fixed width and height div that needs to contain text. If the text exceeds the size of the div, I want it to paginate with dots at the bottom of the page indicating each page, similar to slideshow functionality. Are t ...