element-props

Normalize access to element attributes/properties.

Usage no npm install needed!

<script type="module">
  import elementProps from 'https://cdn.skypack.dev/element-props';
</script>

README

element-props test size

Normalize access to element attributes/properties.

npm i element-props

import props from 'element-props.js'

let el = document.getElementById('my-element')
el.props = props(el, { z: Number })

// numeric
el.props.x = 1
el.getAttribute('x') // '1'
el.props.x // 1

// boolean
el.setAttribute('disabled', '')
el.props.disabled // true
el.props.disabled = false
el.getAttribute('disabled') // null

// functions
el.props.onclick = e => ()

// spread
{...el.props} // { y: false, x: 1, id: 'my-element' }

API

props(element, propTypes?, onchange?)

Create props for an element, with optional propTypes = { propName: Type }.
Type is any data class like Number, Boolean, String, Array, Object, Data, RegExp, or string => data function like JSON.parse (used for Array and Object).

el.props = props(el, {n:Number, b:Boolean, o:Object, a:Array, s:String, d:Date}, (key, val) => {})
el.props.n = '1'
el.setAttribute('b', '')
el.s = 'abc'
el.setAttribute('a', '1,2,3')
el.setAttribute('o', '{foo:"bar"}')

{...el.props} // {n: 1, b: true, s: 'abc', o: {foo:'bar'}, a: [1,2,3]}

props handle input elements - text, checkbox, select:

el.props = document.querySelector('#checkbox')
el.props.value = true

el.value // 'on'
el.checked // true
el.props.value // true
el.getAttribute('value') // 'on'
el.getAttribute('checked') // ''

parse(string, Type?)

Convert string value into defined type or detect type automatically (tiny auto-parse).

import { parse } from './element-props.js'

parse('true', Boolean) // true
parse('123') // 123
parse('1,2,3', Array) // [1, 2, 3]
parse('{ a: 1, b: 2 }', Object) // { a: 1, b: 2}

prop(el, key, value)

Set key prop/attribute value depending on value type.

  • on* property can only be a function.
  • onEvt === onevt.
  • style can only be an object.
  • id can only be a string.
  • Empty strings are considered booleans: <a disabled />a.props.disabled === true

polyfill

Add props to all HTML elements by including augment for Element.prototype.props:

import 'element-props/augment.js'

document.body.id = 'my-body'
document.body.props // { id: 'my-body' }

Design

Internally uses Proxy, (no IE11 support, but in theory possible with MutationObserver fallback)

Inspired by this tweet with spreading hint.

See also

License

ISC © Dmitry Iv.