Skip to content
This repository was archived by the owner on Mar 2, 2020. It is now read-only.

Creating Elements

dev-nicolaos edited this page Apr 11, 2019 · 2 revisions

FSLDOM's newEl() function greatly extends the document.createElement() method.

Syntax

fD.newEl(elementType:string [, options:object])

  • { string } elementType - Matches the type of element that will be created (e.g. 'p' -> <p></p>)
  • { object } options - Defines additional optional properties for the created element
    • { string OR array } classList - sets element.className
    • { string } id - sets element.id
    • { string } html - sets element.innerHTML
    • { string } text - sets element.textContent (ignored if option.html is set)
    • { object } data - creates data attributes (element.dataset) where each property corresponds to a new data attribute
      • Each property's key maps to the name of the data attribute, and should be camelCased
        • Example: options.data.itemId creates data-item-id attribute on element
    • { object } listeners - adds event listeners to element, using the object's keys as the name of the event, and the values as the callback function
    • { string } src - used to set element.src (ignored if elementType is not 'img')
    • { string } alt - used to set element.alt (ignored if elementType is not 'img')
    • { string } href - sets element.href (ignored if elementType is not 'a')
    • { string } target - sets element.target (ignored if elementType is not 'a')
Return Value

Returns the newly created HTML element

Examples

Create a generic element

  let siteHeader = fD.newEl('header', {
    id: 'site-header',
    data: {
      createdAt: (new Date()).toDateString(),
    },
    html: `<a href="index.html">Site Name</a>`,
  });

Create an img element

  let imgElem = fD.newEl('img', {
    src: 'path/to/kitty-picture.png',
    alt: 'Funny Cat Photo',
    classList: 'gallery-img overlay',
  });

Create a hyperlink element

  let linkElem = fD.newEl('a', {
    href: 'https://google.com',
    text: 'Google',
    target: '_blank',
  });

Create an button w/listener

  let button = fD.newEl('button', {
    text: 'Log Random Number',
    listeners: {
      click(e) => {
        console.log(Math.random());
      }
    },
  });

Clone this wiki locally