Cherry
Cherry

Reputation: 33544

Why string assignment in javaScript is case insensitive?

I have create simple html page with one button that change its color when clicked:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button onclick="if (this.style.backgroundColor == 'Red') {
        this.style.backgroundColor = 'Green'
    }
    else {
        this.style.backgroundColor = 'Red'
    }
     alert(this.style.backgroundColor)">
    ok
</button>
</body>
</html>

It is surprising for me that alert(this.style.backgroundColor) return red instead of Red. Why? There is an assignment this.style.backgroundColor = 'Red' and in this Red start with capital letter.

Upvotes: 0

Views: 68

Answers (4)

Allen Chak
Allen Chak

Reputation: 1950

According to W3C, the color unit (color names) are case-insensitive.

4.1. Basic color keywords

The list of basic color keywords is: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. The color names are case-insensitive.

http://www.w3.org/TR/css3-color/#colorunits

Upvotes: 0

xdazz
xdazz

Reputation: 160853

This is not just assigning a string to a variable, but assigning a string to an object's property.

Object's property could has custom setter/getter behaviors.

this.style is a CSSStyleDeclaration object which has the backgroundColor setter/getter implementation with native code.

An example is:

var o = {a: '',  get foo() {return this.a.toLowerCase();}, set foo(x) {this.a = x;}};
o.foo = 'Red';
console.log(o.foo); // will be 'red'

Upvotes: 0

Quentin
Quentin

Reputation: 943585

Some CSS properties are case insensitive.

Browsers are allowed to normalise them.

Upvotes: 1

Barmar
Barmar

Reputation: 781078

CSS styles aren't saved as literal strings, they're converted to an internal, canonical representation of the style. Color styles are case-insensitive, and the canonical representation is lowercase.

Upvotes: 3

Related Questions