Namespace: CSS:applyStyles

CSS:applyStyles

Source:

Methods

applyStyles(element, styles, crossBrowseropt, nullable, returnCssStyleDeclarationopt, nullable) → {Object|CSSStyleDeclaration}

Applies CSS definitions to an HTMLElement, by providing a plain object of property-value-pairs. Properties may be written as default CSS kebab-case properties such as "margin-left" or as JS camel-cased versions such as "marginLeft".

Providing a real JS number without a unit will be treated as a pixel value, so defining "'line-height' : 0" will actually result in a 1px line-height. To actually set a unit-less value, just set the value as a string: "'line-height' : '0'".

Generally all CSS values are usually strings (this is also the way JS handles this), treating plain numbers as pixels is just a convenience feature, since pixels are most likely to be calculated values, where it is bothersome and error-prone to add the "px" all the time.

To remove a property, just set the value to a nullish value. Deleting a property also tries to remove all vendor prefixed variants.

This function uses CSSStyleDeclaration.setProperty instead of direct style assignments. This means, that the browser itself decides which value to apply, based on the support of the property. This means, the style object will not be polluted with vendor stuff the browser does not support, but this also means, that all non-standard properties might be refused. If you really need to set something out of spec, use direct style assignment instead.

Parameters:
Name Type Attributes Default Description
element HTMLElement

the element to apply the styles to, use null or undefined as value to remove a prop

styles Object

the styles to apply, provided as a plain object, defining property-value-pairs

crossBrowser Boolean <optional>
<nullable>
false

set this to true, to automatically generate vendor-prefixed versions of all provided properties

returnCssStyleDeclaration Boolean <optional>
<nullable>
false

set this to true, return the CSSStyleDeclaration of the element after the style application, rather than the plain object

Source:
Throws:
  • error if element is not an HTMLElement

  • error if styles is not a plain object

Returns:
the applied/active styles
Type
Object | CSSStyleDeclaration
Example
applyStyles(document.body, {backgroundColor : red, transition : 'all 200ms'}, true);
applyStyles(document.querySelector('main'), {'font-family' : 'serif'}, false, true);