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 elementcss([propertyName, ...])returns an object with each requested property as a key and its computed valuecss(propertyName, value)writes the value to every matched element's inline stylecss(propertyName, fn)callsfn(index, currentValue)for each matched element with the element bound asthis;undefinedfrom the function leaves that element unchangedcss(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
undefinedor an empty object, and the set forms are a no-op that still returns the chain