Code Monkey home page Code Monkey logo

from-html.js's Introduction

from-html

JavaScript Style Guide

A tiny utility function to get element references directly from a HTML string.

Why?

If you want to create a somewhat complex element tree with JS you may have found yourself writing something like this:

const overlay = document.createElement('div')
const content = document.createElement('div')
const cancelBtn = document.createElement('button')
const confirmBtn = document.createElement('button')

overlay.classList.add('modal__overlay')
content.classList.add('modal__content')
cancelBtn.classList.add('modal__cancel-btn')
confirmBtn.classList.add('modal__confirm-btn')

content.textContent = 'Some message'
cancelBtn.textContent = 'Cancel'
confirmBtn.textContent = 'Confirm'

overlay.appendChild(content)
overlay.appendChild(cancelBtn)
overlay.appendChild(confirmBtn)

cancelBtn.addEventListener('click', () => {/* ... */})
// ...
document.body.appendChild(overlay)

Now this is pretty verbose, and you can't immediately see the tree structure from just looking at the code. This looks somewhat better:

const overlay = document.createElement('div')

modal.innerHTML = `
  <div class="modal__overlay">
    <div class="modal__content">Some message</div>
    <button class="modal__cancel-btn">Cancel</button>
    <button class="modal__confirm-btn">Confirm</button>
  </div>
`

const content = overlay.querySelector('.modal__content')
const cancelBtn = overlay.querySelector('.modal__cancel-btn')
const confirmBtn = overlay.querySelector('.modal__confirm-btn')

... but it's still quite verbose, and you have to keep the query selectors in sync with the markup. So here's how it looks like using fromHTML():

const {
  overlay,
  content,
  cancelBtn,
  confirmBtn
} = fromHTML(`
  <div class="modal__overlay" ref="overlay">
    <div class="modal__content" ref="content">Some message</div>
    <button class="modal__cancel-btn" ref="cancelBtn">Cancel</button>
    <button class="modal__confirm-btn" ref="confirmBtn">Confirm</button>
  </div>
`)

Installation

Install like usual:

yarn add from-html

Then include it in your JS like

import fromHTML from 'from-html'

Or if you prefer the old-fashioned way:

<script src="./node_modules/from-html/lib/from-html.js"></script>

Usage

fromHTML(htmlString [, options])

The values of the ref attributes will get mapped to the property names of the returned object; it's also possible to get an array of elements (not a node list!) by appending square brackets to the ref name:

const names = ['Jane', 'John', 'Jimmy']

const { list, items } = fromHTML(`
  <ul ref="list">
    ${names.map(name => `<li ref="items[]">${name}</li>`).join('')}
  </ul>
`)

Instead of a HTML string it's also possible to pass an ID selector:

<script type="text/template" id="my-template">
  <ul ref="list">
    <li ref="items[]">Jane</li>
    <li ref="items[]">John</li>
    <li ref="items[]">Jimmy</li>
  </ul>
</script>
const { list, items } = fromHTML('#my-template')

It's possible to pass an DOM Element too:

<div id="my-element">
  <ul ref="list">
    <li ref="items[]">Jane</li>
    <li ref="items[]">John</li>
    <li ref="items[]">Jimmy</li>
  </ul>
</div>
// list and items are references to existing dom
const { list, items } = fromHTML(document.getElementById('my-element'))

In the optional second argument the following options can be specified:

  • refAttribute: String -- the attribute to get the element references from; defaults to ref
  • removeRefAttribute: Boolean -- whether to remove that attribute afterwards; defaults to true

For example, if you want to keep the ref attribute you might use data-* attributes for HTML compliance:

const { button } = fromHTML(`
  <button data-ref="button">Click me!</button>
`, {
  refAttribute: 'data-ref',
  removeRefAttribute: false
})

License

MIT @ m3g4p0p 2018

from-html.js's People

Contributors

m3g4p0p avatar

Watchers

James Cloos avatar Tomasz Kociołek avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.