@knno/dom
TypeScript icon, indicating that this package has built-in type declarations

1.1.9 • Public • Published

A small kit to simplify DOM operation.

Install

npm i @knno/dom

Wrap existing elements

// query by selector 
dom.query('div.some-class > #id1')
// warp dom elements to Nodes object
const a = document.createElement('div')
const b = document.createElement('div')
dom.wrap(a)
dom.wrap(a, b)
dom.wrap(...document.querySelectorAll('div'))

Build DOM tree

// create a element and specify class name
dom.new('div', 'class1', 'class2', someClassName ...) 
dom.new('div', 'class1 class2')
// or
dom.div('class1', 'class2' ...)
dom.span('class1 class2 class3', someClassName)
...
// Example:
let input;
dom.div('container').css({
  display: 'flex',
  flexDirection: 'column',
}).append(
  dom.div('header').text('Title'),
  dom.div('content').append(
    dom.input().name('search').ref((ipt) => input = ipt),
    dom.button().text('Search').on('click', () => {
      const keyword = input.value();
      // do search operation ...
    })
  )
).appendTo(document.body)

Convert HTML string to Nodes object

dom.html('<div>example</div>')

Can work with jsdom

const JSDom = require('jsdom')
const { createDom } = require('@knno/dom')

const jsDom = new JSDom.JSDOM();
const doc = jsDom.window.document;
const dom = createDom(doc)
...

console.log(jsDom.serialize());

Support JSX

Enable JSX option.

// Modify your tsconfig.json, add jsx related fields as follow:
{
  "compilerOptions": {
    // ...
    "moduleResolution": "nodenext",
    "jsx": "react",
    "jsxFactory": "h",
    "jsxFragmentFactory": "fragment",
  }
}

TS code:

// index.tsx
import { dom } from '@knno/dom';
import { h, fragment } from '@knno/dom/jsx';

interface MyProp {
  title: string;
}

// create component by jsx
function C1(prop: MyProp) {
  return (
    <div>{prop.title}</div>
  )
}

// create component without jsx
function C2(prop: MyProp) {
  return dom.div().text(prop.title);
}

// use jsx fragments
function C3() {
  return (
    <>
      <C1 title="hello 3" />
      <C2 title="hello 4" />
    </>
  );
}

// entry
(
  <main>
    <div onclick={() => console.log('click 1')}>
      <C1 title="hello 1" />
    </div>
    <div style={{ color: 'red' }}>
      <C2 title="hello 2" />
    </div>
    <div class="some class">
      <C3 />
    </div>
  </main>
).appendTo(document.body);

Support server side render

import { renderToString } from '@knno/dom';
import { h, fragment } from '@knno/dom/jsx';

const text = renderToString(() => <div>Hello world!</div>)
console.log(text);
// or send text to client

Readme

Keywords

Package Sidebar

Install

npm i @knno/dom

Weekly Downloads

2

Version

1.1.9

License

MIT

Unpacked Size

52.7 kB

Total Files

9

Last publish

Collaborators

  • thor.qin