node package manager



Greenkeeper badge

Sauce Test Status

Build Status

Common utilities for CanJS projects


dom {Object}

A collection of modules that operate on DOM.


can-util/dom/ajax/ajax function


  1. settings {Object}: Configuration options for the AJAX request. The list of configuration options is the same as for jQuery.ajax.
  • returns {Promise}: A Promise that resolves to the data.

can-util/dom/child-nodes/child-nodes function


Get all of the childNodes of a given node.

var stache = require("can-stache");
var childNodes = require("can-util/child-nodes/child-nodes");
var html = "<div><h1><span></span></h1></div>";
var frag = stache(html)();
console.log(childNodes(frag)[0].nodeName); // -> DIV 
  1. node {Object}: The Node that you want child nodes for.

className {Object}

Allows querying and manipulation of classes on HTML elements

var className = require("can-util/dom/class-name/class-name");
var fooDiv = document.createElement("div");
className.add(fooDiv, "foo");
fooDiv.outerHTML; //-> '<div class="foo"></div>' 

Object, cls)

Add a class name to a DOM node if it is not already there., "container");
  1. className {String}: A string representing a single class name token
  • returns {void}:, cls)

Determine wheter a DOM node has a given class name.

var isContainer =, "container");
  1. className {String}: A string representing a single class name token
  • returns {Boolean}: true if the element's class attribute contains the token, false otherwise., cls)

Remove a class name from a DOM node if it exists on the node, "container");
  1. className {String}: A string representing a single class name token
  • returns {void}:

data {Object}

Allows associating data as a key/value pair for a particular DOM Node.

var domData = require("can-util/dom/data/data");


  • returns {Number}: The value of the element's unique CID

    Set a unique identifier for the dom node, using the undefined property., key)

Remove data from an element previously added by set, "metadata");, key)

Get data that was stored in a DOM Node using the specified key.

var metadata =, "metadata");
  1. key {String}: A string used as a unique key for storing data associated with this DOM Node.

  • returns {Number}: The value of the element's unique CID

    Return the previously set unique identifier for the dom node., key, value)

  1. name {String}: the key to store the value under
  2. value {*}: the value to store under the key

Set data to be associated with a DOM Node using the specified key. If data already exists for this key, it will be overwritten., "metadata", {
  foo: "bar"

can-util/dom/dispatch/dispatch function, event, args, bubbles)

Dispatch an event on an element.

  1. event {Object|String}: An object specifies options applied to this event.
  2. args {Array}: Arguments passed into this event.
  3. bubbles {Boolean}: Specifies whether this event should bubble (by default it will).

can-util/dom/document/document function


  1. document {Object}: An optional document-like object to set as the context's document

Optionally sets, and returns, the document object for the context.

var documentShim = { getElementById() {...} };
var domDocument = require("can-util/dom/data/data");

events {Object}

Allows you to listen to a domEvent and special domEvents.

var domEvents = require("can-util/dom/events/events");


attributes {events}

Adds a listenable "attributes" event to DOM nodes, which fires when the node's attributes change.


delegateEvents {events}

Add delegate listeners to DOM events. Delegated listeners use a selector on an ancestor element to determine when to fire the event for an item. This can help cases where large numbers of similar DOM nodes are added into a DOM subtree, since event handlers do not have to be attached to each new node.


inserted {events}

This event fires when nodes are added as descendants of the attached element


can-util/dom/events/make-mutation-event/make-mutation-event function

makeMutationEvent(specialEventNae, mutationNodesProperty)
  1. specialEventName {String}: the event to handle as a mutation observer-based event
  2. mutationNodesProperty {String}: the property of interest in a DOM mutation

This function provides a simple interface to bind the DOM events interface to the mutation observer interface, by firing an event when a matching mutation is generated by the client

removed {events}

This event fires when descendant elements of the bound element are detached or destroyed.


can-util/dom/frag/frag function

Convert a String, HTMLElement, documentFragment, or contentArray into a documentFragment.

frag: function(item, doc)

  1. item {String|HTMLElement|documentFragment|contentArray}:

  2. doc {Document}: an optional DOM document in which to build the fragment

  • returns {documentFragment}:

mutate {Object}

Mutate an element by appending, inserting, and removing DOM nodes. Use this so that on the server "inserted" will be fired.

var mutate = require("can-util/dom/mutate/mutate");
var el = document.createElement("div");
el.addEventListener("inserted", function(){
  console.log("Inserted was fired!");
});, el);

Object, child)

Used to append a node to an element and trigger the "inserted" event on all of the newly inserted children. Since mutated takes an array we convert the child to an array, or in the case of a DocumentFragment we first convert the childNodes to an array and call inserted on those., ref, child)

Like mutate.appendChild, used to insert a node to an element before a reference node and then trigger the "inserted" event., child)

Like mutate.appendChild, used to insert a node to an element before a reference node and then trigger the "removed" event., child)

Like mutate.appendChild and mutate.removeChild, used to replace a node with another node and trigger "removed" on the removed element and "inserted" on the inserted elements.

js {Object}

Utilities for manipulating JavaScript data structures.


can-util/js/assign/assign function

assign(target, source)

A simplified version of Object.assign, which only accepts a single source argument.

var assign = require("can-util/js/assign/assign");
var obj = {};
assign(obj, {
  foo: "bar"
console.log(; // -> "bar" 
  1. target {Object}: The destination object. This object's properties will be mutated based on the object provided as source.
  2. source {Object}: The source object whose own properties will be applied to target.
  • returns {Object}: Returns the target argument.

can-util/js/base-url/base-url function


Get and/or set the "base" (containing path) of the document.

var baseUrl = require("can-util/js/base-url/base-url");
console.log(baseUrl());           // -> "http://localhost:8080" 
console.log(baseUrl(baseUrl() + "/foo/bar")); // -> "http://localhost:8080/foo/bar" 
console.log(baseUrl());           // -> "http://localhost:8080/foo/bar" 
  1. setUrl {String}: An optional base url to override reading the base URL from the known path.
  • returns {String}: Returns the set or computed base URL

can-util/js/cid/cid function

cid(object, optionalObjectType)

Get a unique identifier for the object, optionally prefixed by a type name.

Once set, the unique identifier does not change, even if the type name changes on subsequent calls.

var cid = require("can-util/js/cid/cid");
var x = {};
var y = {};
console.log(cid(x, "demo")); // -> "demo1" 
console.log(cid(x, "prod")); // -> "demo1" 
console.log(cid(y));         // -> "2" 
  1. object {Object}: The object to uniquely identify.
  2. name {String}: An optional type name with which to prefix the identifier
  • returns {String}: Returns the unique identifier

can-util/js/deep-assign/deep-assign function

deepAssign(target, [ ... sources ])

Assign properties from a source object to a target object, deeply copying properties that are objects or arrays.

var deepAssign = require("can-util/js/deep-assign/deep-assign");
var dest = deepAssign({}, {
  obj: {
        foo: "bar"
}, {
  arr: [{ hello: "world" }]
console.log(; // -> "bar" 
  1. target {Object}: The target object who's properties will be assigned from the source objects.
  2. source {Object}: Source objects from which properties will be assigned to the target object. Sources will be copied deeply; meaning any object or array properties will be traversed and copied (like a clone).

can-util/js/deparam/deparam function


  1. params {String}: a form-urlencoded string of key-value pairs
  • returns {Object}: The params formatted into an object

    Takes a string of name value pairs and returns a Object literal that represents those params.

    var deparam = require("can-util/js/deparam/deparam");
    console.log(JSON.stringify(deparam("?foo=bar&number=1234"))); // -> '{"foo" : "bar", "number": 1234}' 
    console.log(JSON.stringify(deparam("#foo[]=bar&foo[]=baz"))); // -> '{"foo" : ["bar", "baz"]}' 
    console.log(JSON.stringify(deparam("foo=bar%20%26%20baz"))); // -> '{"foo" : "bar & baz"}' 

can-util/js/diff/diff function

diff(oldList, newList)

  1. oldList {ArrayLike}: the array to diff from
  2. newList {ArrayLike}: the array to diff to
  • returns {Array}: a list of Patch objects representing the differences

    Returns the difference between two ArrayLike objects (that have nonnegative integer keys and the length property) as an array of patch objects.

    A patch object returned by this function has the following properties:

    • index: the index of newList where the patch begins
    • deleteCount: the number of items deleted from that index in newList
    • insert: an Array of items newly inserted at that index in newList
    var diff = require("can-util/js/diff/diff");
    console.log(diff([1], [1, 2])); // -> [{index: 1, deleteCount: 0, insert: [2]}] 
    console.log(diff([1, 2], [1])); // -> [{index: 1, deleteCount: 1, insert: []}] 

can-util/js/diff-object/diff-object function

diffObject(oldObject, newObject)

  1. oldObject {Object}: the object to diff from
  2. newObject {Object}: the object to diff to
  • returns {Array}: an array of object-patch objects

    Find the differences between two objects, based on properties and values

    The object-patch object format has the following keys:

    • property: the property key on the new object
    • type: the type of operation on this property: add, remove, or set
    • value: the new value (if type is "add" or "set")
    var diffObject = require("can-util/js/diff-object/diff-object");
    console.log(diffObject({a: 1, b: 2}, {b: 3, c: 4})); // -> 
      [{property: "a", type: "remove"},
       {property: "b", type: "set": value: 3},
       {property: "c", type: "add", "value": 4}]

can-util/js/each/each function

each(elements, callback, context)

Loop over each element in an Array-Like data structure.

  1. elements {Object|ArrayLike}:

  2. callback {function(element, key, elements)}:

  3. context {Object}: the context object

  • returns {ArrayLike}: the orignal array of elements

     var each = require("can-util/js/each/each");
     each([2,1,0], function(i) { console.log(this[i]); }, [4,5,6]); // -> 6 \n 5 \n 4 

can-util/js/global/global function


Returns the global that this environment provides. It will be one of:

  • Browser: window
  • Web Worker: self
  • Node.js: global
var GLOBAL = require("can-util/js/global/global");
var g = GLOBAL();
// In a browser 
console.log(=== window); // -> true 
  • returns {Object}: The global object for this JavaScript environment.

can-util/js/import/import function

importModule(moduleName, parentName)

var importModule = require("can-util/js/import/import");
  // module was imported 
  1. moduleName {String}: The module to be imported.
  2. parentName {String}: A parent module that will be used as a reference for resolving relative module imports.
  • returns {Promise}: A Promise that will resolve when the module has been imported.

can-util/js/is-array-like/is-array-like function


Determines if an object is "array like", meaning it can be looped over. Any object with a .length property is array like.

var isArrayLike = require("can-util/js/is-array-like/is-array-like");
// Arrays 
console.log(isArrayLike([{ foo: "bar" }])); // -> true 
// Strings 
console.log(isArrayLike("some string")); // -> true 
// Objects with .length property 
console.log(isArrayLike({ length: 11 })); // -> true 
// Numbers and Booleans are not. 
console.log(isArrayLike(true)); // -> false 
console.log(isArrayLike(13)); // -> false 
  1. obj {*}: Any object type.
  • returns {Boolean}: True, if the object is similar to an array.

can-util/js/is-browser-window/is-browser-window function


Returns true if the code is running within a Browser window. Use this function if you need special code paths for when running in a Browser window, a Web Worker, or another environment (such as Node.js).

var isBrowserWindow = require("can-util/js/is-browser-window/is-browser-window");
var GLOBAL = require("can-util/js/global/global");
if(isBrowserWindow()) {
  console.log(GLOBAL() === window); // -> true 
  • returns {Boolean}: True if the environment is a Browser window.

can-util/js/is-empty-object/is-empty-object function


Used to determine if an object is an empty object (an object with no enumerable properties) such as {}.

var isEmptyObject = require("can-util/js/is-empty-object/is-empty-object");
console.log(isEmptyObject({})); // -> true 
console.log(isEmptyObject({ a: 1 })); // -> false 
var obj = {};
Object.defineProperty(obj, "foo", {
    enumerable: false,
    value: "bar"
console.log(isEmptyObject(obj)); // -> true 
  1. obj {Object}: Any object.
  • returns {Boolean}: True if the object is an object with no enumerable properties.

can-util/js/is-node/is-node function

Determines if your code is running in Node.js.


var isNode = require("can-util/js/is-node/is-node");
var GLOBAL = require("can-util/js/global/global");
if(isNode()) {
  console.log(GLOBAL() === global); // -> true 
  • returns {Boolean}: True if running in Node.js

can-util/js/is-plain-object/is-plain-object function


Attempts to determine if an object is a plain object like those you would create using the curly braces syntax: {}. The following are not plain objects:

  1. Objects with prototypes (created using the new keyword).
  2. Booleans.
  3. Numbers.
  4. NaN.
var isPlainObject = require("can-util/js/is-plain-object/is-plain-object");
// Created with {} 
console.log(isPlainObject({})); // -> true 
// new Object 
console.log(isPlainObject(new Object())); // -> true 
// Custom object 
var Ctr = function(){};
var obj = new Ctr();
console.log(isPlainObject(obj)); // -> false 
  1. obj {Object}:
  • returns {Boolean}:

can-util/js/is-promise/is-promise function


Determines if an object is a Promise.

var isPromise = require("can-util/js/is-promise/is-promise");
var promise = new Promise(function(resolve){
console.log(isPromise(promise)); // -> true 
console.log(isPromise("foo bar")); // -> false 
  1. obj {Object}: An object to be tested.
  • returns {Boolean}: True if the object is a Promise.

can-util/js/is-string/is-string function

Determines if the provided argument is a string.


var isString = require("can-util/js/is-string/is-string");
console.log(isString("foo")); // -> true 
console.log(isString(String("foo")); // -> true 
console.log(isString({})); // -> false 
  1. obj {*}: An object to test if is a string.
  • returns {Boolean}: True if the object is a string.

can-util/js/is-web-worker/is-web-worker function

Determines if the code is running with a Web Worker.


var isWebWorker = require("can-util/js/is-web-worker/is-web-worker");
var GLOBAL = require("can-util/js/global/global");
if(isWebWorker()) {
  console.log(GLOBAL() === self); // -> true 
  • returns {Boolean}: True if running in a Web Worker.

can-util/js/join-uris/join-uris function

Join together a URI path to a base.

joinURIs(base, href)

Provides a convenient way to join together URIs handling relative paths.

var joinURIs = require("can-util/js/join-uris");
var base = "";
var href = "../../images/foo.png";
var res = joinURIs(base, href);
console.log(res); // -> 
  1. base {String}:

  2. href {String}:

  • returns {String}: The result of joining the two parts.

can-util/js/make-array/make-array function


  1. arr {ArrayLike}: any array-like object
  • returns {Array}: a JavaScript array object with the same elements as the passed-in ArrayLike

    makeArray takes any array-like object (can-list, NodeList, etc.) and converts it to a JavaScript array

can-util/js/param/param function

Serialize an object into a query string.


Serializes an object or array into a query string useful for making Ajax requests or the browser. param handles nested objects and arrays. It uses encodeURIComponent to escape values and keys.

param({a: "b", c: "d"}) //-> "a=b&c=d" 
param({a: ["X","Y"]})   //-> "a[]=X&a[]=Y" 
  1. params {Object}: [description]
  • returns {String}: [description]

can-util/js/set-immediate/set-immediate module


  1. cb {function}:

Polyfill for setImmediate() if it doesn't exist in the global context

string {Object}

String utilities used by CanJS libraries



  1. content {String}: a string
  • returns {String}: the string safely HTML-escaped

string.getObject(name, roots, add)

  1. name {String}: a String of dot-separated keys, representing a path of properties
  2. roots {Object|Array}: the object to use as the root for property based navigation
  3. add {Boolean}: if true, add the parts at each step as new objects
  • returns {*}: the value at the property path descending from roots

    Return the result of descending the path name through the properties of the object or objects roots

    If roots is an Array, each element of the array is evaluated, in order, until the path is found in an element's properties (and properties-of-properties, etc.). Otherwise roots is evaluated as the root object, returning either the object at the property path descended from roots or undefined if any subpath is not found.

    A path is a dot-delimited sequence of zero or more property names, such that "" means "the property 'bar' of the object at the property 'foo' of the root." An empty path returns the first object in roots if it's an array, roots itself otherwise.

    If add is true and path is not found in any roots, a matching path that resolves to an empty object is added to the first object in roots if roots is an array, roots itself otherwise.

    var string = require("can-util/js/string/string");
    console.log(string.getObject("a.b.c", {a: {b: {c: "foo"}}})); // -> "foo" 
    console.log(string.getObject("a.b.c", {a: {}})); // -> undefined 
    console.log(string.getObject("a.b", [{a: {}}, {a: {b: "bar"}}])); // -> "bar" 


  1. s {String}: the string to capitalize
  • returns {String}: the supplied string with the first character uppercased if it is a letter

    var string = require("can-util/js/string/string");
    console.log(string.capitalize("foo")); // -> "Foo" 
    console.log(string.capitalize("123")); // -> "123" 


  1. str {String}: the string to camelCase
  • returns {String}: the supplied string with hyphens removed and following letters capitalized.

    var string = require("can-util/js/string/string");
    console.log(string.camelize("foo-bar")); // -> "fooBar" 
    console.log(string.camelize("-webkit-flex-flow")); // -> "WebkitFlexFlow" 


  1. str {String}: a string in camelCase
  • returns {String}: the supplied string with camelCase converted to hyphen-lowercase digraphs

    var string = require("can-util/js/string/string");
    console.log(string.hyphenate("fooBar")); // -> "foo-bar" 
    console.log(string.hyphenate("WebkitFlexFlow")); // -> "Webkit-flex-flow" 


  1. str {String}: a string in camelCase
  • returns {String}: the supplied string with camelCase converted to underscore-lowercase digraphs

    var string = require("can-util/js/string/string");
    console.log(string.underscore("fooBar")); // -> "foo_bar" 
    console.log(string.underscore("HTMLElement")); // -> "html_element" 

string.sub(str, data, remove)

  1. str {String}: a string with {curly brace} delimited property names
  2. data {Object}: an object from which to read properties
  • returns {String|null}: the supplied string with delimited properties replaced with their values if all properties exist on the object, null otherwise

    If remove is true, the properties found in delimiters in str are removed from data.

    var string = require("can-util/js/string/string");
    console.log(string.sub("foo_{bar}", {bar: "baz"}})); // -> "foo_baz" 
    console.log(string.sub("foo_{bar}", {})); // -> null 

can-util/js/string-to-any/string-to-any function

Turns a string representation of a primitive type back into the associated primitive.


Examines the provided string to see if it can be converted to a primitive type. Supported arguments are:

  • "true"
  • "false"
  • "null"
  • "undefined"
  • "NaN"
  • "Infinity"
  • Any Number
  • Any String
stringToAny("NaN"); // -> NaN 
stringToAny("44.4"); // -> 44.4 
stringToAny("false"); // -> false 
  1. string {String}: A string to convert back to its primitive type.
  • returns {*}: The primitive representation of the provided string.


Making a Build

To make a build of the distributables into dist/ in the cloned repository run

npm install
node build

Running the tests

Tests can run in the browser by opening a webserver and visiting the test.html page. Automated tests that run the tests from the command line in Firefox can be run with

npm test