Implement jQuery css()

Hard45 minLinkedIn

Prompt

Build a small version of jQuery's css() method. You expose a function jq(selector) that returns an object with a css method. The method is overloaded: the same name reads styles in some calls and writes styles in others. The shape of the arguments tells you which.

<div>
<p id="test" style="color: red; opacity: 1;">
Hello World
</p>
</div>

Read one property (from the first matched element):

jq('#test').css('color');
// "rgb(255, 0, 0)"

Read several properties at once:

jq('#test').css(['color', 'opacity']);
// { color: "rgb(255, 0, 0)", opacity: "1" }

Set one property on every matched element:

jq('#test').css('color', 'green');

Set per-element via a function:

function setColor(index, currentValue) {
return index % 2 === 0 ? 'orange' : 'green';
}
jq('p').css('color', setColor);

If the function returns undefined for an element, that element is left alone.

Set several properties via an object:

jq('p').css({ color: 'red', opacity: 1 });

The set forms return the chain object so calls can be chained: jq(el).css('color', 'red').css('opacity', 0.5).

Requirements

  • css(propertyName) returns the computed value of the property for the first matched element
  • css([propertyName, ...]) returns an object with each requested property as a key and its computed value
  • css(propertyName, value) writes the value to every matched element's inline style
  • css(propertyName, fn) calls fn(index, currentValue) for each matched element with the element bound as this; undefined from the function leaves that element unchanged
  • css(properties) writes every key of the object to every matched element's inline style
  • Set calls return the chain so jq(el).css(a).css(b) works
  • If the selector matches no elements, the get forms return undefined or an empty object, and the set forms are a no-op that still returns the chain