• This repository has been archived on 16/Jul/2021
  • Stars
    star
    128
  • Rank 281,044 (Top 6 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated over 8 years ago

Reviews

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

Repository Details

micro DOM selector library that maps queries to native get commands

saltjs

salt.js is micro DOM selector library. Minified, it comes in at 255 bytes! (with attribution...)

Here is a quick video showing it off

No longer the smallest

It looks like there are a couple ways to do this in even less code...

Other versions

Tomasz Żełudziewicz Versions version 1 version 2 version 3

Michał Wachowskis fork.

How it works

It uses an array string to map different queries you pass through it to their native get functions.

// get by id
$('#iddiv');
// get by class name
$('.classdiv');
// get by element name
$('@namediv');
// get by element tag name
$('=div');
// get element by query selector
$('*div div.inside');
// getAttribute of name
$('#iddiv').getAttribute('name');
// getAttribute of name from nodelist
$('.classdiv')[0].getAttribute('name');

Fun with Mapping

WARNING!

You need to extend native code to produce these functions. This is not recommended. Salt is really a micro selector library not a substitution for jQuery or anything else.

Here are a couple of little things you can do to shorten some syntax.

// probably the most useful and allows $('#iddiv').find('.inside')
window.Element.prototype.find = function(selector) {
  return $(selector, this);
};

// doing a find in a NodeList doesnt really work. I had a function that
// would look inside and get the element but it was pretty big and
// required recusive searching inside NodeLists. So I would suggest just
// using a '*' selection method
window.NodeList.prototype.find = function find(elem) {
  console.error('You cannot find in a NodeList. Just use $(*selector %s)', elem);
  return this;
};

// another useful one for doing $('.inside').each()
window.NodeList.prototype.each = Array.prototype.forEach;

// $().attr('prop', 'value') support
window.Element.prototype.attr = function(name, value) {
  if(value) {
    this.setAttribute(name, value);
    return this;
  } else {
    return this.getAttribute(name);
  }
};

window.NodeList.prototype.attr = function(name, value) {
  this.each(function(el) {
    if(value) {
      el.setAttribute(name, value);
    } else {
      return el.getAttribute(name);
    }
  });
  return this;
};

// $().css('prop', 'value') support
window.Element.prototype.css = function(prop, value) {
  if (value) {
    this.style[prop] = value;
    return this;
  } else {
    return this.style[prop];
  }
};

window.NodeList.prototype.css = function(prop, value) {
  this.each(function(el) {
    el.css(prop, value);
  });
  return this;
};

// $().on('event', function(el){});
window.Element.prototype.on = function(eventType, callback) {
  eventType = eventType.split(' ');
  for (var i = 0; i < eventType.length; i++) {
    this.addEventListener(eventType[i], callback);
  }
  return this;
};


window.NodeList.prototype.on = function(eventType, callback){
  this.each(function(el){
    el.on(eventType, callback);
  });
  return this;
};

// $().addClass('name');
window.NodeList.prototype.addClass = function(name){
  this.each(function(el) {
    el.classList.add(name);
  });
  return this;
};

window.Element.prototype.addClass = function(name) {
  this.classList.add(name);
  return this;
};

// $().removeClass('name');
window.NodeList.prototype.removeClass = function(name){
  this.each(function(el) {
    el.classList.remove(name);
  });
  return this;
};

window.Element.prototype.removeClass = function(name) {
  this.classList.add(name);
  return this;
};

window.Element.prototype.hasClass = function(name) {
  // contains? how annoying!
  return this.classList.contains(name);
};

window.NodeList.prototype.first = function() {
  // if this is more than one item return the first
  return (this.length < 2) ? this : this[0];
};

window.NodeList.prototype.last = function() {
  // if there are many items, return the last
  return (this.length > 1) ? this[this.length - 1] : this;
};

So you can keep doing this with native commands and get something pretty close to jQuery.

If you used all of those you could turn this:

var items = document.getElementById('iddiv').querySelectorAll('.inside');
for (var i = items.length - 1; i >= 0; i--) {
  items[i].setAttribute('name', 'Guy Dude Bro');
}

into this:

$('#iddiv').find('.inside').each(function(elem){
  elem.attr('name', 'Guy Dude Bro');
});

jsPerf testing

jsPerf test

The reason I don't just use querSelectorAll for everything is because it is slower than the native get commands*.

See this jsperf test

Yes, I know that this library is slower than native gets, sometimes massively. But the point here is to beat querySelectorAll and it does it's job by that standard.

I don't like FOO for selecting BAR

Cool. Change it up! You can choose your own mapping methods if you want. Just change the key in the 'matches' object and you are good.

X returns an array!

That is because you are using a selector that has a live nodelist collection.

License

(The MIT License)

Copyright (c) 2015 James Doyle [email protected]

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

vue-drag-and-drop

A for Vue.js directive for providing drag and drop capabilities to elements and data
JavaScript
389
star
2

vue-file-upload-component

A simple file upload component for Vue.js. Emits events for XHR Upload Progress for nice progress bars.
JavaScript
233
star
3

zepto-dragswap

a micro plugin for having swappable/dragable/sortable lists and grids
JavaScript
156
star
4

nuxt-firebase-auth

An example of using Nuxt with Firebase to auth users without a server
Vue
122
star
5

vue-ajax-form-component

A Vue.js component for creating simple AJAX forms.
JavaScript
86
star
6

google-form-styling

A stylesheet to be used if you want to create your own theme for a google form
CSS
81
star
7

swoole-examples

Examples on how to use the Swoole async PHP framework
PHP
63
star
8

laravel-scout-sonic

Sonic driver for Laravel Scout
PHP
54
star
9

simplebinder

simplebinder is a zero dependency one-way databinder for javascript
CSS
51
star
10

git-website-workflow

a script that creates a git-capable website workflow
Shell
43
star
11

ki.extend.js

extend ki.js with some fancy prototypes
JavaScript
30
star
12

angular-through-iframe

How to use angular.js through an iframe
HTML
29
star
13

phalconphp-completions

A set of completions for the Phalcon PHP Framework made for Sublime Text 3
JavaScript
28
star
14

sublime-to-atom-snippets

This little script allows you to convert sublime text snippets to atom editor cson snippets.
JavaScript
26
star
15

pyro-module-generator

Create modules for PyroCMS 2.2 by just filling in a simple form. Built with PhalconPHP.
PHP
20
star
16

kube-styl

Kube CSS Framework by Imperavi, converted from LESS to Styl/Rework.
CSS
16
star
17

atom-jquery-snippets

This is a snippets package for Atom. It is a conversion of an old jQuery snippets for sublime text.
CoffeeScript
16
star
18

vue-omnibar

Create modal popups that emulate omnibar, command palette, open anywhere, or other "search and act" functions/features
Vue
16
star
19

sublime-node-snippets

A collection of completions/snippets for node.js v8.x
JavaScript
14
star
20

pico_slider

create sliders inside the Pico CMS by listing the images in a folder
PHP
14
star
21

grunt-jsfmt

a grunt task for the jsfmt tool
JavaScript
14
star
22

pico_get_by_filename

A Pico CMS plugin to grab content by the filename
PHP
14
star
23

devicesocket

an example of socket.io sending the device orientation between the connected clients
CSS
14
star
24

Lico

Lico is Pico re-written using Luvit for Lua
Lua
13
star
25

vue-ga-directive

A directive for accessing the Google Analytics window.ga object by using params/attributes
JavaScript
13
star
26

nudeproject

A starting point for new web projects, meant for building simple sites or landing pages.
CSS
13
star
27

rework-shade

Lighten and darken plugin for the Rework CSS preprocessing library. Parity with the Stylus version.
JavaScript
12
star
28

pmenu

pmenu is a Path-like menu written in Javascript and CSS3. It uses translate3d not pos:abs top/left
JavaScript
11
star
29

phalcon-security

A simple demo of the Phalcon Security and Session usage
PHP
11
star
30

pyro-image-select

Visually select images using a field type in PyroCMS
PHP
9
star
31

slim-starter

A Slim Framework starting project with JWT, controllers, models, migrations, seeds, caching, and testing
PHP
9
star
32

php-naivechain

An implementation of a block chain in PHP inspired by the naivechain npm package
PHP
7
star
33

laravel-helper-completions

A set of completions for Laravel 5 helper functions
7
star
34

macaron-example

An example project using the Macaron framework for Go
Go
7
star
35

phileAdmin

a take on an admin panel for PhileCMS
JavaScript
7
star
36

pico_download

Force files to download in PicoCMS
PHP
6
star
37

phalcon-micro-start

a more practical example of the start of a Phalcon micro application
PHP
6
star
38

jquery-morphdom

A jQuery wrapper for morphdom - a fast and lightweight DOM diffing/patching (without the virtual part)
JavaScript
6
star
39

atom-monokai-dark

A dark monokai theme for the Atom editor
CSS
6
star
40

xdebug-devtools

A Chrome extension for showing your Xdebug errors inside DevTools instead of inline in your page.
PostScript
6
star
41

php-faker-completions

Sublime Text completions for the fzaninotto/Faker package
JavaScript
5
star
42

php-socket-chat

A PHP websocket chat app. Uses Rachet.
PHP
5
star
43

pyro-list-field

A List field type for PyroCMS
PHP
5
star
44

pyro-github-markdown

Github flavoured markdown field type for PyroCMS
PHP
5
star
45

pyro-blurb-field

Create small components with Title, Image and Body sections.
PHP
5
star
46

grunt-highlight

Use highlight.js via a Grunt task
JavaScript
5
star
47

sublime-liquid

A collection of syntaxes and completions for Liquid (and Shopify) templates
4
star
48

pwa-skeleton

A simple Progressive Web App skeleton project
JavaScript
4
star
49

pico_useragent

Parse the user agent string of the current visitor and expose an array of values to use in your templates
PHP
4
star
50

Swipe.js-WordPress-Plugin

Plugin for WordPress based on the Swipe.js library by Brad Birdsall
PHP
4
star
51

CommonRegexPHP

Find a lot of kinds of common information in a string
PHP
4
star
52

luvstache

Mustache templates for Luvit
Lua
4
star
53

pyro-pagewidgets-field

Add widgets to a page by selecting the widget and then ordering it.
PHP
4
star
54

vue-tailwind-starter

A boilerplate for starting new Vue projects with Tailwind support
JavaScript
4
star
55

nextjs-watermelondb-example

Example of Next.js with WatermelonDB
TypeScript
4
star
56

pyro-twitter-widget

A twitter widget for PyroCMS. Supports oAuth v1.1 API.
PHP
3
star
57

pyro-swipe-module

PyroCMS Swipe.js module
PHP
3
star
58

ohdoylerules.com

Source for ohdoylerules.com
HTML
3
star
59

assemble-starter

A starting point for any of my static assemble sites. Includes extra JS, CSS, and Grunt tasks.
JavaScript
3
star
60

threejs-stars

a modified demo of a threejs rotating star system
JavaScript
3
star
61

simple-page-checker

Run GoogleChrome/puppeteer over a list of pages and check for errors in them
JavaScript
3
star
62

parsetweet

This function can parse tweets and wrap @ mentions, #hashtags, and URLs in link tags.
PHP
3
star
63

vue-stateful-form

Create a form that escalates all events to the top level and supports v-model
TypeScript
3
star
64

vue-pretty-print-bytes-filter

A filter for Vue.js to format bytes into a nice human-readable format.
JavaScript
3
star
65

omf-plugin-fnm

Completion support for Schniz/fnm
Shell
3
star
66

slim-example

A set of examples for using the Slim 3 PHP framework
CSS
2
star
67

ki.deferred.js

jQuery style $.deferred and $.when support.
JavaScript
2
star
68

faktory-example

Example usage for contribsys/faktory with node.js and docker.
JavaScript
2
star
69

vuex-stateful-url

StatefulURL is a Vuex plugin that can read and write the state from a query string
JavaScript
2
star
70

jquery-plugin-snippets

A bunch of jQuery plugin snippets for Sublime Text 2 via shichuan/javascript-patterns/jquery-plugin-patterns
2
star
71

clean-css-chrome-app

Clean CSS packaged app for Google Chrome
JavaScript
2
star
72

vuex-crosstab

CrossTab syncs Vuex state across same-origin tabs
JavaScript
2
star
73

jquery.doodal.js

a very simplistic modal plugin for jQuery. Has custom events, allows stacking, and is powered by CSS transitions.
CSS
2
star
74

golang-completions

A set of completions for Go 1.8.x functions, types, interfaces, and methods
2
star
75

a11y

A site for checking if color combinations pass AA or AAA
Vue
2
star
76

pico_ajax

A PicoCMS plugin that renders a template based on data in the config file.
PHP
2
star
77

rework-math

math plugin for the Rework CSS preprocessing library.
JavaScript
2
star
78

sublime-twig

A collection of syntaxes and completions for Twig templates
2
star
79

post-socket

Turn a POST request (JSON) to Websocket event
Go
1
star
80

browser-sniffer

A simple class to detect the browser and the platform (operating system) that the user is using
PHP
1
star
81

lit-slugify

Lit package for generating URL slugs
Lua
1
star
82

Paw-FetchGenerator

Paw Code Generator Extension for browser Fetch
JavaScript
1
star
83

lit-merge

Lit module to merge table 1 with table 2, handle nested tables
Lua
1
star
84

sublime-vlang

A collection of syntaxes and completions for vlang(v)
V
1
star
85

OceanicNext-Mac-Terminal-Theme

An OceanicNext theme for the default OSX terminal
Shell
1
star
86

webpack-loader-starter

A starting point for creating Webpack loaders based on the tutorial from the Webpack site
JavaScript
1
star
87

mandarin-cards

Trying to make a little flash card game for simple phrases in Mandarin
JavaScript
1
star
88

socket-chat-example

a small demo of a socket chat app that also has a shared counter and name support.
JavaScript
1
star
89

digitalocean-spaces-example

An example on how to use DigitalOcean Spaces with S3 libraries
JavaScript
1
star
90

omf-plugin-dart

A dart and flutter plugin for Oh My Fish
Shell
1
star
91

vscode-snippet-to-sublime-snippet

A small CLI tool to convert VSCode Snippet files into Sublime Text 3 snippets
Dart
1
star
92

go-github-example

An example go app that fetches github repositories based on usernames
Go
1
star
93

pyro-scrape-plugin

A plugin to scrape a web page for specific selectors
PHP
1
star
94

sublime-react-snippets

A few snippets for React hooks
1
star
95

james2doyle

1
star
96

project-splitting

Experiments and proof-of-concepts for how to share code across projects locally
Vue
1
star
97

mithril-testing

A more advanced sample of the mithril todo app
HTML
1
star
98

vue-toggle

Vue component to create UI and UX elements with toggleable states
JavaScript
1
star
99

pico-grunt-themeing

A starting point for building themes for PicoCMS. Uses Grunt with watch/livereload and node-sass.
JavaScript
1
star
100

pyro-sniffer-plugin

Sniff information from the user agent for use in the frontend. Useful for adding classes or conditional loading.
PHP
1
star