Thursday, July 13

Creating and Styling Multiple Elements in JavaScript


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[style] = childElm;
    } else {
      switch (style){
        case "id": = value;           break;
        case "class":
        case "className": elm.className = value;    break;
        default:[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); Example


Post a Comment