• This repository has been archived on 15/Nov/2017
  • Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    JavaScript
  • Created almost 14 years ago
  • Updated over 12 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DOM builder with multiple output formats

DOMBuilder travis_status qunit_tests

DOMBuilder takes some of the pain out of dynamically creating HTML content in JavaScript and supports generating multiple types of output from the same inputs.

Yes, there are a million builder libraries about. DOMBuilder's goals are to:

  • Make it easier to write JavaScript components which can be shared between the frontend and backend - newforms is an example of such a component, which aims to share validation code between the two.
  • Make it easier to switch from DOM Element output to HTML String output if performence becomes an issue, by providing mock DOM objects and event registration helpers when generating HTML from the exact same input.

Demos

  • Fragile - uses DOMBuilder's template mode and its template inheritance to create a CRUD admin with templates which can also be rendered on the backend with Node.js.
  • DOMBuilder.build() sandbox - play around with DOMBuilder.build(), with switchable DOM and HTML output modes.
  • Reddit posts - uses JSONP to display a feed of posts from Reddit:
  • Demo page - small examples of using the range of the DOMBuilder API

Install

Browsers

Compressed builds of DOMBuilder are available to suit various needs:

DOM and HTML
For creation of mixed content, with DOM Mode as the default output format.
DOM only
For creation of DOM Elements, with DOM Mode as the default output format.
HTML only
For creation of HTML Strings, with HTML Mode as the default output format.
Templates
For templating, with mixed output and DOM Mode as the default output format.

Dependencies

There are no required dependencies, but if jQuery (>= 1.4) is available, DOMBuilder will make use of it when creating DOM Elements and setting up their attributes and event handlers.

If not, DOMBuilder will fall back to using some less comprehensive workarounds for cross-browser DOM issues and use the traditional event registration model for compatibility.

Node.js

DOMBuilder can be installed as a Node.js module via npm. The Node.js build includes Template mode and has HTML mode as the default output format.

Install:

npm install DOMBuilder

Import:

var DOMBuilder = require('DOMBuilder')

Quick Guide

DOMBuilder provides a convenient, declarative API for generating HTML elements, via objects which contain functions named for the HTML element they create:

with(DOMBuilder.dom) {
  var article =
    DIV({'class': 'article'}
    , H2('Article title')
    , P('Paragraph one')
    , P('Paragraph two')
    )
}

Every element function also has a map function attached to it which allows you to easily generate content from a list of items:

var el = DOMBuilder.html
function shoppingList(items) {
  return el.OL(el.LI.map(items))
}
>>> shoppingList(['Cheese', 'Bread', 'Butter'])
<ol><li>Cheese</li><li>Bread</li><li>Butter</li></ol>

You can control map output by passing in a callback function:

function opinionatedShoppingList(items) {
  return el.OL(el.LI.map(items, function(item, attrs, loop) {
    if (item == 'Cheese') attrs['class'] = 'eww'
    if (item == 'Butter') return el.EM(item)
    return item
  }))
}
>>> opinionatedShoppingList(['Cheese', 'Bread', 'Butter'])
<ol><li class="eww">Cheese</li><li>Bread</li><li><em>Butter</em></li></ol>

If you want to use this API to go straight to a particular type of output, you can do so using the functions defined in DOMBuilder.dom and DOMBuilder.html, as demonstrated above.

If you want to be able to switch freely between output modes, or you won't know which kind of output you need until runtime, you can use the same API via DOMBuilder.elements, controlling what it outputs by setting the DOMBuilder.mode flag to 'dom' or 'html', or calling a function which generates content using DOMBuilder.withMode:

var el = DOMBuilder.elements
function shoutThing(thing) {
  return el.STRONG(thing)
}
>>> DOMBuilder.mode = 'html'
>>> shoutThing('Hello!').toString()
<strong>Hello!</strong>
>>> DOMBuilder.withMode('dom', shoutThing, 'Hey there!')
[object HTMLStrongElement]

This is useful for writing libraries which need to support outputting both DOM Elements and HTML Strings, or for unit-testing code which normally generates DOM Elements by flipping the mode in your tests to switch to HTML String output.

DOMBuilder also supports using its output modes with another common means of defining HTML in JavaScript code, using nested lists (representing elements and their contents) and objects (representing attributes), like so:

var article =
  ['div', {'class': 'article'}
  , ['h2', 'Article title']
  , ['p', 'Paragraph one']
  , ['p', 'Paragraph two']
  ]

You can generate output from one of these structures using DOMBuilder.build, specifying the output mode:

>>> DOMBuilder.build(article, 'html').toString()
<div class="article"><h2>Article title</h2><p>Paragraph one</p><p>Paragraph two</p></div>

>>> DOMBuilder.build(article, 'dom').toString()
[object HTMLDivElement]

You can also generate these kinds of structures using the element functions defined in DOMBuilder.array.

This is just a quick guide to what DOMBuilder can do - dive into the full documentation to find out about the rest of its features, such as:

Development

Version 2.1: DOMBuilder.template

DOMBuilder is a modular library, which supports adding new output modes and feature modes as plugins.

Version 2.1 will add Template mode to DOMBuilder and the templating API should be considered unstable until Version 2.2.

  • Based on Django templates, including their powerful template inheritance.

  • Templates are defined entirely in JavaScript code, still discovering the pros and cons of this as I go:

    Pros

    • Easier to create new template tags, as there's no parsing step.
    • You can spin template creation out into DSL-like functions, which is expressive and very flexible, using functions to build up sections using logically named functions which create template contents based on data structures, rather than copying and pasting chunks of annotated markup or trying to use includes.

    Cons

    • More unwieldy to edit than text-based templates, but manageable if you follow some layout guidelines.
    • More awkward to do things like optional attributes and arbitrary chunks of HTML, since HTML is defined at the element level using DOMBuilder's element functions.

In this live example, template inheritance is being used to minimise the effort required to create basic admin CRUD screens using Sacrum.

Version 2.0.1 released on August 6th, 2011

See News for DOMBuilder for what's new and backwards-incompatible changes since 1.4.*.

MIT License

Copyright (c) 2011, Jonathan Buchanan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

nwb

A toolkit for React, Preact, Inferno & vanilla JS apps, React libraries and other npm modules for the web, with no configuration (until you need it)
JavaScript
5,572
star
2

react-hn

React-powered Hacker News client
JavaScript
2,179
star
3

control-panel-for-twitter

Browser extension which gives you more control over your Twitter timeline and adds missing features and UI improvements - available for desktop and mobile browsers
JavaScript
1,924
star
4

react-maskedinput

Masked <input/> React component
JavaScript
730
star
5

newforms

Isomorphic form-handling for React
JavaScript
642
star
6

msx

JSX for Mithril.js 0.x
JavaScript
362
star
7

react-heatpack

A 'heatpack' command for quick React development with webpack hot reloading
JavaScript
347
star
8

inputmask-core

Standalone input mask implementation, independent of any GUI
JavaScript
304
star
9

babel-plugin-react-html-attrs

Babel plugin which transforms HTML and SVG attributes on JSX host elements into React-compatible attributes
JavaScript
177
star
10

isomorphic-lab

Isomorphic React experimentation
JavaScript
144
star
11

react-auto-form

Simplifies getting user input from forms via onChange and onSubmit events, using DOM forms APIs
JavaScript
116
star
12

react-router-active-component

Factory function for React components which are active for a particular React Router route
JavaScript
113
star
13

get-form-data

Gets form and field data via form.elements
JavaScript
106
star
14

react-lessons

Tool for creating and taking interactive React tutorials
JavaScript
103
star
15

react-examples

React… examples…
JavaScript
98
star
16

ad-hoc-reckons

JavaScript
85
star
17

control-panel-for-youtube

Browser extension which gives you more control over YouTube by adding missing options and UI improvements - for desktop & mobile browsers
JavaScript
81
star
18

remote_control_for_vlc

A VLC remote control written with Flutter
Dart
77
star
19

react-octicon

A GitHub Octicons icon React component
JavaScript
75
star
20

gatsby-plugin-dark-mode

A Gatsby plugin which handles some of the details of implementing a dark mode theme
JavaScript
68
star
21

react-filtered-multiselect

Filtered multi-select React component
JavaScript
61
star
22

redux-todomvc-es5

ES5 version of the Redux todomvc example
JavaScript
59
star
23

react-router-form

<Form> is to <form> as <Link> is to <a>
JavaScript
56
star
24

redux-action-utils

[DEPRECATED] Factory functions for reducing action creator boilerplate (pun not intended)
JavaScript
48
star
25

newforms-bootstrap

Components for rendering a newforms Form using Bootstrap 3
JavaScript
48
star
26

package-config-checker

Checks if your dependencies have package.json files config or an .npmignore for packaging
JavaScript
47
star
27

obs-bounce

OBS script to bounce a scene item around, DVD logo style or throw & bounce with physics
Lua
44
star
28

lifequote

React port of a life insurance quick quoting application
JavaScript
39
star
29

newforms-examples

Examples repository for newforms / React
JavaScript
32
star
30

ideas-md

A float-to-the-top ideas log built with React
JavaScript
32
star
31

djangoffice

Project management/CRM for small offices - Clients, Jobs, Tasks, Rates, Activities, Timesheets, Contacts, Invoices etc. etc.
Python
30
star
32

tabata_timer

A Tabata training interval timer written with Flutter.
Dart
30
star
33

react-gridforms

React components for Gridforms form layout
JavaScript
29
star
34

newforms-gridforms

Grid Forms integration for newforms
CSS
27
star
35

comments-owl-for-hacker-news

Browser extension which makes it easer to follow comment threads on Hacker News across multiple visits, allows you to annotate and mute users, and other UI tweaks and mobile UX improvements
JavaScript
27
star
36

astro-lazy-youtube-embed

Embed YouTube videos with a static placeholder which only embeds when you click
Astro
26
star
37

reactodo

Multiple localStorage TODO lists, built with React
JavaScript
25
star
38

forum

A basic Django forum app with metaposts; uses redis for stats/tracking
Python
25
star
39

react-plain-editable

[DEPRECATED] React component for editing plain text via contentEditable
JavaScript
21
star
40

ui-lib-samples

Misc impls of functionality with various JavaScript UI libs
HTML
15
star
41

react-dsl

Generate React components as DSLs for structural markup, such as that of CSS frameworks
CSS
14
star
42

soclone

The beginnings of a Stack Overflow clone
Python
14
star
43

concur

Sugar for infectious JavaScript inheritance, metaprogramming & mixins
JavaScript
14
star
44

gulp-msx

Precompile Mithril views which use JSX into JavaScript
JavaScript
14
star
45

manage-twitter-engagement

Manage "engagement" on Twitter by moving retweets and algorithmic tweets to their own lists
JavaScript
14
star
46

hta-localstorage

Basic localStorage implementation for Internet Explorer HTML Applications (HTA)
JavaScript
12
star
47

caveat-utilitor

Personal GtHub repo status badges
12
star
48

sublime-sort-javascript-imports

Sublime Text package for sorting selected JavaScript import/require() lines by module name
Python
11
star
49

greasemonkey

User scripts
JavaScript
11
star
50

nwb-from-create-react-app

Examples of using nwb as an alternative to ejecting from create-react-app
JavaScript
11
star
51

nwb-sass

Sass plugin for nwb
JavaScript
11
star
52

templates

Reusable templates for various kinds of projects
HTML
10
star
53

sacrum

One codebase, two environments - single-page JavaScript apps in the browser, forms 'n links webapps on Node.js for almost-free
JavaScript
10
star
54

isomorph

Shared utilities for browsers and Node.js
JavaScript
9
star
55

update-object

Mirror of Facebook's update() immutability helper
JavaScript
9
star
56

substitute

Edits Twitter typos using s/this/that/ expressions
JavaScript
7
star
57

react-playground

React component for creating interactive coding playgrounds with preset examples
JavaScript
7
star
58

dinnertime

Cooking timer & scheduler with spoken instructions
JavaScript
7
star
59

validators

Validators which can be shared between browsers and Node.js
JavaScript
7
star
60

nwb-react-tutorial

An implementation of the React Tutorial using nwb's middleware
JavaScript
6
star
61

sublime-react-snippets

Sublime Text snippets for writing React components
JavaScript
6
star
62

eslint-config-jonnybuchanan

Personal ESLint setup as a single devDependency
JavaScript
6
star
63

insin.github.io

Static project & demo hosting
JavaScript
6
star
64

react-objecteditor

An <ObjectEditor/> React component
JavaScript
5
star
65

nwb-thinking-in-react

An implementation of the Thinking in React tutorial using nwb
JavaScript
5
star
66

nwb-examples

Examples of configuring nwb
JavaScript
5
star
67

stargaze

Watch a GitHub repo's star count, with change notifications on your desktop
JavaScript
5
star
68

nwb-less

Less plugin for nwb
JavaScript
4
star
69

babel-preset-proposals

A Babel 7 preset to manage experimental proposal plugin dependencies and usage
JavaScript
4
star
70

urlresolve

Resolves paths against URL patterns
JavaScript
4
star
71

shilefare

Dead simple local, temporary file sharing with Node.js
JavaScript
4
star
72

couch25k

Java MIDlet which tracks intervals for the Couch-to-5k running program
Java
4
star
73

chainable-check

Create React.PropTypes-alike validators with an isRequired property
JavaScript
4
star
74

yak-stacker

An app for tracking your Yak Stack during programming sessions
4
star
75

cdogs-wii

Wii port of C-Dogs SDL using SDL Wii
C
4
star
76

deduped-babel-presets

[DEPRECATED] Babel 6 presets with shared dependencies manually deduplicated for npm2 compatibility
JavaScript
3
star
77

react-suggest

React components for implementing suggested completions
JavaScript
3
star
78

rllmuk-really-ignore-users

Really ignore ignored users, and ignore users in specific topics
JavaScript
3
star
79

react-split-date-input

Reusable split date input React component
JavaScript
3
star
80

njive

Node.js wrapper for the Jive API
JavaScript
3
star
81

bootstrap-4-nwb

Example app from "Using Bootstrap 4 from source with React and nwb"
CSS
3
star
82

react-node-time-tracker

A React clone of a Vue tutorial app
JavaScript
3
star
83

redbox-noreact

A fork of redbox-react which doesn't import React
JavaScript
3
star
84

POWDER-wii

Port files for the Wii version of POWDER ( http://www.zincland.com/powder/ )
C++
3
star
85

just-dadjokes

Just the jokes from /r/dadjokes
JavaScript
3
star
86

gulp-flatten-requires

Flattens relative require('./<path>/<module>') calls to require('./<module>')
JavaScript
3
star
87

pixel-shifter

A React component for pixel-shifting text elements
JavaScript
3
star
88

event-listener

Simple function for addEventListener() vs. addEvent()
JavaScript
3
star
89

lmms

Linux MultiMedia Studio working directory
Python
3
star
90

buildumb

Ultra-dumb exporter of Node.js modules for use in the browser
JavaScript
2
star
91

models

Models, models, everywhere. In the client and in the server.
JavaScript
2
star
92

countdown-file

Writes a countdown to a text file every second
JavaScript
2
star
93

django-vgdb

[OLD] Videogame database, opinion & story collector - begat django-mptt
Python
2
star
94

iswydt

Tumblejobs
JavaScript
2
star
95

twitter-searchite

Quick creation of sites driven by polling a Twitter search
JavaScript
2
star
96

stackoverflow

Code from investigating/answering StackOverflow questions
CSS
2
star
97

cookdandbombd-really-ignore-users

Really ignore ignored users
JavaScript
2
star
98

mixinstance

Mix new things into an instance's prototype chain
JavaScript
2
star
99

successcrm

JavaScript
2
star
100

rllmuk-ignore-topics

Hide topics and forums you're not interested in on the Rllmuk forum
JavaScript
2
star