Thursday, July 13

Dynamically Style Element from Variable ( JavaScript )


Web browsers have become more and more capable, more powerful, in the recent years. With web pages becoming more complicated and more reliant on JavaScript and CSS I find our CSS files are becoming larger and harder to keep orderly.

Lately, most of the HTML elements in any given project I program, are being created in JavaScript code. Now that the elements are being created in JavaScript, I wanted an easy way to style the elements as well. Making it easier to create more modular components, and free code from having separate CSS files.


Now with a simple function, which I pass the element variable, and a JavaScript object variable with the styles defined, I can easily change the style without having to look through the CSS files.

Settings Variable

var style = {
        position: 'absolute',
        top: '50px',
        left: '50px',
        width: '30%',
        height: '30%',
        background: '#eee',
        border: '1px dashed #333'

The Function
function styleElement( elm, styles ){
  for(var style in styles){[style] = styles[style];
  return elm;

The Example Code
var root = {
        width: '100%',
        height: '100%',
        margin: '0px',
        padding: '0px',
        overflow: 'hidden'

function init() {
  let html = document.querySelector('html')
    , body = document.querySelector('body')
    , elm = document.createElement('div')
  body.appendChild( elm );
  styleElement( html, root );
  styleElement( body, root );
  styleElement( elm, styles );

window.addEventListener('load', init); Example

See the Pen Style Element from jsObject by Failed Sleep (@FailedSleep) on CodePen.


Post a Comment