• Stars
    star
    277
  • Rank 148,875 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 8 years ago

Reviews

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

Repository Details

💉 Lean DOM Manipulation

dominus.png

Lean DOM Manipulation

This isn't a drop-in replacement for jQuery, but rather a different implementation. Dominus is jQuery minus the cruft, with a footprint of ~4kB minified and gzipped, vs the ~33kB in jQuery. Dominus uses sektor as its selector engine of choice, which is a drop-in replacement for Sizzle, but tens of times smaller in exchange for a more limited feature-set.

Just like with jQuery, Dominus exposes a rich API that's chainable to the best of its ability. The biggest difference with jQuery at this level is that the Dominus wrapper is a real array. These arrays have been modified to include a few other properties in their prototype, but they don't change the native DOM array. See poser for more details on that one. All of this means you can .map, .forEach, .filter, and all of that good stuff that you're used to when dealing with JavaScript collections, and at the same time you get some extra methods just like with jQuery.

Install

Using Bower

bower install -S dominus

Using npm

npm install -S dominus

API

The API in Dominus begins with the methods listed below, which allow you to grab an object instance.

Static Methods

These are the static methods provided by Dominus. Consider these the entry point, just like the methods exposed by jQuery on $.

dominus()

Returns an empty Dominus collection.

dominus(HTMLElement)

Wraps the HTMLElement object in a Dominus collection.

dominus(Dominus)

Returns the Dominus collection, as-is.

dominus(Array)

Returns a Dominus collection with the HTMLElement objects found in the provided array.

dominus('<{tag-name}>')

Returns a Dominus collection after creating an element of the provided tag type name.

dominus(selector, context?)

See dominus.find below.

dominus.find(selector, context?)

Queries the DOM for the provided selector, using sektor. Returns a Dominus collection with HTMLElement objects. If context is provided then the search is restricted to children of context. The context can be either a DOM element, a selector string, or a Dominus object (the first DOM element in the group is used).

dominus.findOne(selector, context?)

Queries the DOM for the provided selector, using sektor. Returns the first matching HTMLElement object, if any. If context is provided then the search is restricted to children of context. The context can be either a DOM element, a selector string, or a Dominus object (the first DOM element in the group is used).

dominus.custom(name, type, filter)

See Custom Event Filters below.

Instance Methods

Once you've gotten yourself a Dominus collection, there's a few more methods you'll get access to. I'll denote array instances as a, where possible.

First off, there's the selection methods.

Navigation API

These methods let you search the DOM for the nodes that you want to manipulate.

a.prev(selector?)

Returns the previous sibling, optionally filtered by a selector.

a.next(selector?)

Returns the next sibling, optionally filtered by a selector.

a.parent(selector?)

Returns the first parent element, optionally filtered by a selector.

a.parents(value?)

Returns all parent elements, optionally filtered by another Dominus collection, a DOM element, or a selector.

a.children(value?)

Like .find, but only one level deep. Optionally filtered by another Dominus collection, a DOM element, or a selector.

a.find(selector)

Queries the DOM for children of the elements in the array, using the provided selector. Returns a single Dominus collection containing all of the results.

a.findOne(selector)

Queries the DOM for children of the elements in the array, using the provided selector. Returns the first matching HTMLElement object, if any.

a.where(selector)

Returns a subset of the elements in the array that match the provided selector.

a.is(selector)

Returns whether at least one of the elements in the array match the provided selector.

Then there's also the attribute manipulation API.

Attribute Methods

These methods let you modify DOM element attributes or properties.

a.html(value?)

If a value is provided then every element in the Dominus collection gets assigned that HTML value, then a is returned for chaining. If you don't provide a value, you get the HTML contents of the first node in the Dominus collection back.

a.text(value?)

If a value is provided then every element in the Dominus collection gets assigned that plain text value, then a is returned for chaining. If you don't provide a value, you get the plain text contents of the first node in the Dominus collection back. In the case of elements that can be checked, the native value property is used instead.

a.value(value?)

If a value is provided then every element in the Dominus collection gets assigned that input value, then a is returned for chaining. If you don't provide a value, you get the input value of the first node in the Dominus collection back. In the case of elements that can be checked, the native checked property is used instead.

a.attr(name)

The name attribute's value is returned, for the first element in the collection.

a.attr(name, value)

Every element in the collection gets assigned value to the attribute property name. Passing null or undefined as the value will remove the attribute from the DOM element entirely.

a.attr(attributes)

The attributes map is used to assign every property-value pair to the attributes in every element.

a.addClass(value)

Adds value to every element in the collection. value can either be a space-separated class list or an array.

a.removeClass(value)

Removes value from every element in the collection. value can either be a space-separated class list or an array.

a.setClass(value)

Sets value for every element in the collection. value can either be a space-separated class list or an array.

a.hasClass(value)

Returns true if at least one of the elements in the collection matches every class in value. value can either be a space-separated class list or an array.

a.css(prop)

Gets the CSS property value for prop from the first element in the set of matched elements. camelCase gets converted into hyphen-case.

a.css(prop, value)

Sets the CSS property value for prop to value for every element in the set of matched elements. camelCase gets converted into hyphen-case.

a.css(props)

Sets the CSS property values for every element in the set of matched elements using the provided props map. camelCase gets converted into hyphen-case.

Example:

dominus('body').css({ color: 'blue', width: 600 });

You can physically alter the DOM, using the methods listed in the next category.

DOM Manipulation

a.on(type, filter?, fn)

Attaches the event handler fn for events of type type on every element in the Dominus collection. You can also pass in a list of event types, such as click dragstart, and both events get the event listener attached to them.

The filter? argument is optional, and you can use it to provide a selector that will filter inputs. This is known as event delegation. The example below will bind a single event listener that will fire only when child nodes matching the .remove selector are clicked.

dominus('.products').on('click', '.remove', removeProduct);

a.once(type, filter?, fn)

Meant for when you want to listen for an event only once. This method is identical to a.on(type, filter?, fn), except the event listener will be removed right before your fn callback is executed.

a.off(type, filter?, fn)

Turns off event listeners matching the event type, the filter selector (if any), and the event handler.

a.emit(type)

Fabricates a synthetic event of type type and dispatches it for each element in the collection. Note that these events are even accessible outside of Dominus.

var el = document.getElementById('dollars');
el.addEventListener('dollarsigns', function () {
  alert('$$$');
});
$(el).emit('dollarsigns');

Custom Event Filters

Dominus allows you to create custom sub-events. For example, you could have a custom click sub-event that only triggers on left clicks; or a custom key press event that only triggers when certain keys are pressed.

Dominus ships with the following custom events.

Event Description
'left-click' Only triggers when a left click happens while no meta keys are pressed (Command, Control)

You can register your own custom events using dominus.custom.

dominus.custom(name, type, filter)

Register a custom event named name. This event will trigger whenever a type event triggers, but only if filter(e) returns true.

As an illustrative example, here's how the left-click custom event is registered.

dominus.custom('left-click', 'click', function (e) {
  return e.which === 1 && !e.metaKey && !e.ctrlKey;
});

Adding or removing event listeners to custom event filters is no different from adding or removing regular event listeners.

$('#home').on('left-click', navigateHome);

a.focus()

Invokes HTMLElement.focus() on the first DOM element in the collection.

a.clone()

Returns a deep clone of the DOM elements in the collection.

a.remove()

Removes the selected elements from the DOM.

a.append(elem)

Inserts the provided elem as the last child of each element in the collection.

a.appendTo(elem)

Inserts every element in the collection as the last children of the provided elem.

a.prepend(elem)

Inserts the provided elem as the first child of each element in the collection.

a.prependTo(elem)

Inserts every element in the collection as the first children of the provided elem.

a.before(elem)

Inserts the provided elem as the previous sibling of each element in the collection.

a.after(elem)

Inserts the provided elem as the next sibling of each element in the collection.

a.beforeOf(elem)

Inserts every element in the collection as the previous siblings of the provided elem.

a.afterOf(elem)

Inserts every element in the collection as the next siblings of the provided elem.

The methods listed below affect the collection itself

Dominus Collection Methods

Besides the fact that Dominus is an out-of-context Array object, meaning you can do all the fun functional programming you're used to, there's a few more methods to manipulate the collection itself.

a.and(...)

Returns a copy of a, adding the result of calling dominus() with the arguments you provided to the current collection.

This means that you can use .and with selectors, a DOM element, an array of DOM elements, or another Dominus collection.

a.but(...)

Returns a copy of a, removing the result of calling dominus() with the arguments you provided from the current collection.

This means that you can use .but with selectors, a DOM element, an array of DOM elements, or another Dominus collection.

a.i(index)

Returns the element at index index, wrapped in a Dominus object. If the index is out of bounds then an empty Dominus collection will be returned.

License

MIT

More Repositories

1

dragula

👌 Drag and drop so simple it hurts
JavaScript
21,936
star
2

es6

🌟 ES6 Overview in 350 Bullet Points
4,328
star
3

rome

📆 Customizable date (and time) picker. Opt-in UI, no jQuery!
JavaScript
2,913
star
4

js

🎨 A JavaScript Quality Guide
2,874
star
5

fuzzysearch

🔮 Tiny and blazing-fast fuzzy search in JavaScript
JavaScript
2,711
star
6

woofmark

🐕 Barking up the DOM tree. A modular, progressive, and beautiful Markdown and HTML editor
JavaScript
1,624
star
7

promisees

📨 Promise visualization playground for the adventurous
JavaScript
1,199
star
8

horsey

🐴 Progressive and customizable autocomplete component
JavaScript
1,167
star
9

css

🎨 CSS: The Good Parts
992
star
10

react-dragula

👌 Drag and drop so simple it hurts
JavaScript
992
star
11

contra

🏄 Asynchronous flow control with a functional taste to it
JavaScript
771
star
12

shots

🔫 pull down the entire Internet into a single animated gif.
JavaScript
728
star
13

insignia

🔖 Customizable tag input. Progressive. No non-sense!
JavaScript
674
star
14

campaign

💌 Compose responsive email templates easily, fill them with models, and send them out.
JavaScript
641
star
15

perfschool

🌊 Navigate the #perfmatters salt marsh waters in this NodeSchool workshopper
CSS
630
star
16

local-storage

🛅 A simplified localStorage API that just works
JavaScript
523
star
17

angularjs-dragula

👌 Drag and drop so simple it hurts
HTML
509
star
18

reads

📚 A list of physical books I own and read
486
star
19

insane

😾 Lean and configurable whitelist-oriented HTML sanitizer
JavaScript
449
star
20

hget

👏 Render websites in plain text from your terminal
HTML
334
star
21

hit-that

✊ Render beautiful pixel perfect representations of websites in your terminal
JavaScript
332
star
22

hash-sum

🎊 Blazing fast unique hash generator
JavaScript
301
star
23

swivel

Message passing between ServiceWorker and pages made simple
JavaScript
294
star
24

trunc-html

📐 truncate html by text length
JavaScript
220
star
25

grunt-ec2

📦 Create, deploy to, and shutdown Amazon EC2 instances
JavaScript
190
star
26

beautify-text

✒️ Automated typographic quotation and punctuation marks
JavaScript
186
star
27

sixflix

🎬 Detects whether a host environment supports ES6. Algorithm by Netflix.
JavaScript
175
star
28

twitter-for-github

🐥 Twitter handles for GitHub
JavaScript
146
star
29

awesome-badges

🏆 Awesome, badges!
JavaScript
124
star
30

prop-tc39

Scraping microservice for TC39 proposals 😸
JavaScript
108
star
31

megamark

😻 Markdown with easy tokenization, a fast highlighter, and a lean HTML sanitizer
JavaScript
104
star
32

diferente

User-friendly virtual DOM diffing
JavaScript
95
star
33

domador

😼 Dependency-free and lean DOM parser that outputs Markdown
JavaScript
86
star
34

proposal-undefined-coalescing-operator

Undefined Coalescing Operator proposal for ECMAScript
77
star
35

dotfiles

💠 Yay! @bevacqua does dotfiles \o/
Shell
75
star
36

assignment

😿 Assign property objects onto other objects, recursively
JavaScript
73
star
37

sektor

📍 A slim alternative to jQuery's Sizzle
JavaScript
65
star
38

map-tag

🏷 Map template literal expression interpolations with ease.
JavaScript
65
star
39

unbox

Unbox a node application with a well-designed build-oriented approach in minutes
JavaScript
61
star
40

hint

Awesome tooltips at your fingertips
JavaScript
60
star
41

but

🛰 But expands your functional horizons to the edge of the universe
JavaScript
59
star
42

kanye

Smash your keyboards with ease
JavaScript
55
star
43

correcthorse

See XKCD for reference
JavaScript
52
star
44

easymap

🗺 simplified use of Google Maps API to render a bunch of markers.
JavaScript
52
star
45

flickr-cats

A demo page using the Flickr API, ServiceWorker, and plain JavaScript
HTML
49
star
46

hubby

👨 Hubby is a lowly attempt to describe public GitHub activity in natural language
JavaScript
46
star
47

ruta3

Route matcher devised for shared rendering JavaScript applications
JavaScript
45
star
48

poser

📯 Create clean arrays, or anything else, which you can safely extend
JavaScript
45
star
49

baal

🐳 Automated, autoscaled, zero-downtime, immutable deployments using plain old bash, Packer, nginx, Node.js, and AWS. Made easy.
Shell
44
star
50

lipstick

💄 sticky sessions for Node.js clustering done responsibly
JavaScript
43
star
51

crossvent

🌏 Cross-platform browser event handling
JavaScript
41
star
52

lazyjs

The minimalist JavaScript loader
JavaScript
39
star
53

spritesmith-cli

😳 Adds a CLI to the spritesmith module
JavaScript
38
star
54

gulp-jsfuck

Fuck JavaScript and obfuscate it using only 6 characters ()+[]!
JavaScript
37
star
55

measly

A measly wrapper around XHR to help you contain your requests
JavaScript
36
star
56

keynote-extractor

🎁 Extract Keynote presentations to JSON and Markdown using a simple script.
AppleScript
35
star
57

hyperterm-working-directory

🖥👷📂 Adds a default working directory setting. Opens new tabs using that working directory.
JavaScript
34
star
58

gitcanvas

🏛 Use your GitHub account's commit history as a canvas. Express the artist in you!
JavaScript
34
star
59

cave

Remove critical CSS from your stylesheet after inlining it in your pages
JavaScript
33
star
60

scrape-metadata

📜 HTML metadata scraper
JavaScript
31
star
61

feeds

🍎 RSS feeds I follow and maintain
31
star
62

suchjs

Provides essential jQuery-like methods for your evergreen browser, in under 200 lines of code. Such small.
JavaScript
30
star
63

ponyedit

An interface between contentEditable and your UI
JavaScript
29
star
64

grunt-grunt

Spawn Grunt tasks in other Gruntfiles easily from a Grunt task
JavaScript
29
star
65

ultramarked

Marked with built-in syntax highlighting and input sanitizing that doesn't encode all HTML.
JavaScript
28
star
66

sell

💰 Cross-browser text input selection made simple
JavaScript
28
star
67

icons

Free icon sets gathered around the open web
27
star
68

insert-rule

Insert rules into a stylesheet programatically with a simple API
JavaScript
26
star
69

hose

Redirect any domain to localhost for convenience or productivity!
JavaScript
26
star
70

ponymark

Next-generation PageDown fork
JavaScript
25
star
71

omnibox

Fast url parsing with a tiny footprint and extensive browser support
JavaScript
25
star
72

estimate

Calculate remaining reading time estimates in real-time
JavaScript
24
star
73

node-emoji-random

Creates a random emoji string. This is as useless as it gets.
JavaScript
24
star
74

sluggish

🐍 Sluggish slug generator that works universally
JavaScript
24
star
75

seleccion

💵 A getSelection polyfill and a setSelection ranch dressing
JavaScript
24
star
76

bullseye

🎯 Attach elements onto their target
JavaScript
23
star
77

vectorcam

🎥 Record gifs out of <svg> elements painlessly
JavaScript
22
star
78

paqui

Dead simple, packager-agnostic package management solution for front-end component developers
JavaScript
22
star
79

grunt-ngdoc

Grunt task for generating documentation using AngularJS' @ngdoc comments
JavaScript
20
star
80

ftco

⚡ Browser extension that unshortens t.co links in TweetDeck and Twitter
JavaScript
19
star
81

jadum

💍 A lean Jade compiler that understands Browserify and reuses partials
JavaScript
19
star
82

trunc-text

📏 truncate text by length, doesn't cut words
JavaScript
16
star
83

flexarea

Pretty flexible areas!
JavaScript
16
star
84

music-manager

📻 Manages a list of favorite artists and opens playlists on youtube.
JavaScript
16
star
85

grunt-integration

Run Integration Tests using Selenium, Mocha, a Server, and a Browser
JavaScript
15
star
86

apartment

🏡 Remove undesirable properties from a piece of css
JavaScript
14
star
87

mongotape

Run integration tests using mongoose and tape
JavaScript
14
star
88

rehearsal

Persist standard input to a file, then simulate real-time program execution.
JavaScript
13
star
89

queso

Turn a plain object into a query string
JavaScript
13
star
90

bitfin

🏦 Finance utility for Bitstamp
JavaScript
13
star
91

pandora-box

🐼 What will it be?
JavaScript
12
star
92

grunt-spriting-example

An example on how to seamlessly use spritesheets with Grunt.
12
star
93

artists

🎤 Big list of artists pulled from Wikipedia.
JavaScript
11
star
94

twitter-leads

🐦 Pull list of leads from a Twitter Ads Lead Generation Card
JavaScript
11
star
95

reaver

Minimal asset hashing CLI and API
JavaScript
11
star
96

atoa

Creates a true array based on `arraylike`, starting at `startIndex`.
JavaScript
10
star
97

BridgeStack

.NET StackExchange API v2.0 client library wrapper
C#
10
star
98

ama

📖 A repository to ask @bevacqua anything.
10
star
99

virtual-host

Create virtual, self-contained `connect` or `express` applications using a very simple API.
JavaScript
10
star
100

banksy

🌇 Street art between woofmark and horsey
JavaScript
10
star