0

I'm developing an app that assigns users different colored text (think Gravatar-like hash-generated user colors) [i.e. HashColors - may have to click "Run with JS"].

To integrate the HashColors script into the larger app, I created a function that sets the .textContent and .style for each user's entry. .textContent appears to work cross-browser, but .style appears to only work in Firefox.

A full example is available at https://jsbin.com/sudave/9/edit?html,console,output (may have to click "Run with JS"), but I'm pretty sure the crux of my problem is within the following function or how I call it:

Element generation function:

var gE = function(selector, value, style) {
    var element = document.querySelector("ul " + selector);
    element.textContent = value || " ";  // <-- works as expected
    element.style = style || "";  // <-- does NOT work as expected !!!
                                  // i.e. works as expected in FF
                                  // does NOT work as expected in Chrome or Safari
    return element;
};

Example element generation function call:

 gE('.name', "White on Purple", "background: rgba(" + color + "); color: white");

where var color = "100, 000, 100, 100";

Can anybody tell me why this works as expected in Firefox, but not in other browsers? Better yet, can anybody make suggestions so that I can get it working cross-browser?

Working as expected in Firefox:

Working as expected in Firefox

NOT working as expected in Chrome:

enter image description here

3
  • 1
    Why not generate a CSS rule instead? Commented Jun 24, 2015 at 22:30
  • @SLaks - First - Thank you for your answer below! To answer your question - because each user (and it's likely there will be many users visible per page) will have their own color, and that color will be used as a background in one context and a text color in a different context, it seemed most appropriate to inline the actual style. (Check out HashColors to get a better idea of what I'm talking about.) Commented Jun 24, 2015 at 23:29
  • It is likely to be more efficient to dynamically generate a CSS stylesheet, especially if new comments might be added later. Commented Jun 25, 2015 at 2:19

1 Answer 1

3

The Element.style property returns an object with a property for each style; not a string.

You should call setAttribute("style", style) instead to actually set the attribute.

Sign up to request clarification or add additional context in comments.

1 Comment

For those interested, here's the corrected example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.