Thursday, July 13

Creating and Styling Multiple Elements in JavaScript


Description

A simple function to make it easy to create and style multiple html elements in JavaScript. Pass this function a JavaScript object with the settings you need create and it will return a element with all children elements created and appended.


The Function

function createAndStyle( styles ){
  var elm = document.createElement('div');
  for(var style in styles){
    let value = styles[style];
    if (typeof( value )==='object') {
      let childElm = createAndStyle( value );
      elm.appendChild(childElm);
      elm[style] = childElm;
    } else {
      switch (style){
        case "id":        elm.id = value;           break;
        case "class":
        case "className": elm.className = value;    break;
        default:          elm.style[style] = value; break;
      }
    }
  }
  return elm;
}


The Example Code

let buttonStyle = {
        display: 'inline-block',
        width: '50px',
        height: '50px',
        background: '#777',
        marginLeft: '10px'
    }
  , SideBar = {
      id: 'sideBar_Root',
      position: 'absolute',
      left: '0px',
      top: '1px',
      width: '298px',
      height: 'calc(100% - 4px)',
      padding: '10px',
      background: '#eee',
      border: '1px dashed #333',
      button1: buttonStyle,
      button2: buttonStyle,
      button3: buttonStyle,
      button4: buttonStyle,
      button5: buttonStyle,
      button6: buttonStyle,
      button7: buttonStyle,
      button8: buttonStyle,
      button9: buttonStyle,
      button10: buttonStyle
    };

function init() {
  let body = document.querySelector('body')
    , elm = createAndStyle( SideBar );
    ;
  body.appendChild( elm );
}

window.addEventListener('load', init);



Codepen.io Example

0 comments :

Post a Comment