atschaal atschaal - 1 year ago 104
Javascript Question

Dynamic <style> tag not applying styles to classes

this seems to be simple - but it's excruciatingly frustrating.

I've built a chat application for a school project. It's .NET signalR and jquery spaghetti. This is not production ready code whatsoever. However, my non-tech family likes to log into it to chat during the day occasionally

Recently traffic has picked up enough that I'd like to differentiate usernames by color. So on adding a user to the chatHub I run something like this:

var color = randomColor({ luminosity: 'dark', count: 1 });
var className = "span.user-name.user" + id.split('-')[0];
$("<style type='text/css'>." + className + "{color:" + color + ";}</style>").appendTo("head");

As you can see I'm using extreme specificity. And I can see the actual
appear in my chrome inspector.

style shown in <code><head></code> in inspector

Unfortunately, the class doesn't seem to affect the actual element. Here's the element in the inspector.

actual element

I'm not entirely sure what the problem is. I've tried adding the following:

  1. Adding to the
    instead of the

  2. Increasing specificity more and more.

  3. Changing it in the inspector.stylesheet (works here).

  4. Ensuring that I didn't start any classes with numbers (CSS 2?)

  5. Running thru CSS validators.

I'm out of ideas of what else to try. I would definitely appreciate it if some css ninja could tell me what I've done wrong here.

P.S. Boy this is embarrassing. Thanks guys!

Answer Source

The way you are building the CSS string is inserting a . before span (which is a tag, not a class). Remove that and all should work:

var color = randomColor({ luminosity: 'dark', count: 1 });
var className = "span.user-name.user" + id.split('-')[0];
$("<style type='text/css'>" + className + "{color:" + color + ";}</style>").appendTo("head");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download