项目作者: ryanmorr

项目描述 :
The ultimate DOM attribute, property, style, data, and event setter
高级语言: JavaScript
项目地址: git://github.com/ryanmorr/attr.git
创建时间: 2020-01-25T01:16:42Z
项目社区:https://github.com/ryanmorr/attr

开源协议:The Unlicense

下载


attr

Version Badge
License
Build Status

The ultimate DOM attribute, property, style, data, and event setter

Install

Download the CJS, ESM, UMD versions or install via NPM:

  1. npm install @ryanmorr/attr

Usage

Import the library:

  1. import attr from '@ryanmorr/attr';

Add an attribute:

  1. attr(element, 'id', 'foo');

Add multiple attributes:

  1. attr(element, {
  2. id: 'foo',
  3. class: 'bar baz qux'
  4. });

Remove an attribute with null or undefined:

  1. attr(element, 'class', null);

Set boolean attributes and properties:

  1. attr(checkbox, 'checked', true);
  2. attr(textfield, 'value', 'foo bar');
  3. attr(element, 'innerHTML', '<span></span>');

Set styles as a string:

  1. attr(element, 'style', 'width: 100px; height: 100px;');

Set styles as an object:

  1. attr(element, 'style', {
  2. width: 100,
  3. height: 100
  4. });

Set CSS custom properties:

  1. attr(element, 'style', 'color: var(--color)');
  2. attr(element, 'style', '--color: red');
  3. attr(element, 'style', {'--color': 'blue'});

Add an event listener:

  1. attr(element, 'onclick', (e) => {
  2. // Handle click event
  3. });

Set data attributes (will automatically convert objects to string):

  1. attr(element, 'data', {
  2. str: 'foo',
  3. num: 123,
  4. bool: true,
  5. object: {foo: 'bar'},
  6. array: [1, 2, 3]
  7. });

Supports functions that return the new value (except when adding an event!). The element and the current value of the attribute are provided as the only 2 parameters:

  1. attr(element, 'class', 'foo bar baz');
  2. element.className; //=> "foo bar baz"
  3. attr(element, 'class', (el, value) => value.split(' ').filter(cls => cls !== 'bar'));
  4. element.className; //=> "foo baz"
  5. attr(element, 'style', {width: 100, height: 100});
  6. element.style.cssText; //=> "width: 100px; height: 100px"
  7. attr(element, 'style', (el, value) => Object.assign({}, value, {height: null}));
  8. element.style.cssText; //=> "width: 100px;"
  9. attr(element, 'data', {foo: [1, 2, 3]});
  10. element.dataset.foo; //=> "[1,2,3]"
  11. attr(element, 'data', (el, value) => ({foo: value.foo.filter(val => val !== 2)}));
  12. element.dataset.foo; //=> "[1,3]"

License

This project is dedicated to the public domain as described by the Unlicense.