Traversty — headache-free DOM collection management and traversal

Traversty is a library-agnostic DOM utility for traversal and element collection manipulation. Traversty doesn't provide any DOM manipulation features; instead, Traversty is used for managing collections of DOM elements and navigating the DOM.

Current file size: 15.7 kB raw, 5.7 kB min, 2.1 kB gzip

Just show me the API!

Traversal

The core DOM traversal methods are inspired by Prototype's excelent "DOM traversal toolkit", you get up(), down(), next() and previous() with optional selector and index arguments, all in a multi-element environment—jQuery-like rather than Prototype's single-element implementation.

In addition, jQuery-compatible traversal methods extend this functionality: parents(), closest(), children(), siblings() and prev() a simple alias for previous().

Collection filtering

Traversty operates on DOM element collections, jQuery-style, so it also gives you methods to filter and manipulate that collection. The filtering methods are designed to be jQuery-compatible. You get: first(), last(), eq(), not(), slice(), filter(), has() and is() (this last method returns a boolean rather than a collection).

Traversty emulates an Array and includes additional methods to help you manage it as if it were one: get(), toArray(), size(), push(), sort(), splice().

Ender integration

Traversty is designed to be integrated in an Ender build, to augment what's already available in Bonzo but can just as easily be used as a stand-alone utility.

$ ender build jeesh traversty

Component integration

You can also install Traversty as a component:

$ component install rvagg/traversty

Wiring in a selector engine is up to you in your component build. You'll need to make one-off call to setSelectorEngine() once you have a selector engine to inject, otherwise Traversty will simply use native querySelectorAll() and matchesSelector() if available. See the setSelectorEngine() for more details on how this works.

var zest = require('zest')
  , $ = require('traversty').setSelectorEngine(zest)

Example usage

This bit of craziness comes from Traversty's integration tests. The bulk of this code is used to test Traversty's integration with Ender where the css() method is provided by Bonzo but there is also a vanilla version with only Qwery for the selector engine and a css() method added using Traversty's aug() method (see the /examples/aug-css.js file for how this is done).

var $ = traversty
$.setSelectorEngine(qwery)
$('#fixtures > ul') // Traversty operates on collections of elements
  .down(0).css('color', 'red')
  .next('li', 1).css('color', 'green')
  .next().down('li', 2).css('color', 'blue')
  .next().down().css('color', 'yellow')
  .up(2).next().css('color', 'purple')
  .siblings(3).css('fontWeight', 'bold')
  .children().css('textDecoration', 'underline')
  .children(1).css('borderLeft', 'solid 5px red')
  .parents('*').filter('ul').css('borderTop', 'dashed 2px green')
  .not('.second').css('borderBottom', 'solid 3px blue')
  .down('.second li').has('span').css('marginTop', '10px')
  .up('ul').eq(-1).css('borderLeft', 'solid 5px orange')
  .closest('#fixtures').down('li').slice(-10,-9).css('fontSize', '25px')
  // Note: the css() method is not native to Traversty but is added with aug()

The return type from the traversty() method is not a true Array but can be used like an array in almost all respects, it has .length and [] subscript element access and other standard Array methods.

API


traversty(element | elements | selector)

traversty() gives you a new Traversty instance containing the elements you provide.

Once you have a collection, you can call any of the Traversty methods on that collection. You can give a single DOM element or an array of DOM elements. If you provide a string argument it will be used as a selector to either query the DOM via the browser's native querySelectorAll() implementation or use a selector engine which you provide (see setSelectorEngine()).

You can pluck individual elements with array accessors (subscript), e.g. traversty(document.body)[0] // → document.body

When included in an Ender build, $(element | elements | selector) does the same thing and all the Traversty methods will be available on the resulting Ender object.


next([selector [, index = 0]])

traversty(elements).next() returns a new Traversty instance containing nextSibling elements according to the arguments provided.

You will get elements that match the given selector (if provided) starting from the nextSibling of the starting element(s), all the way across to the last nextSibling.

If no index or selector is given then you get just the nextSiblings of the elements; i.e. you shift across by one.

If just an index is provided then you'll get the index+1 nextSiblings of the element(s). i.e. index is 0-based, like arrays, 0 is nextSibling and 1 is nextSibling.nextSibling, unless you provide a selector of course, in which case it'll skip over non-matching elements.

If just a selector is provided then no index will be assumed, you'll get all matching nextSibling elements.

Examples

traversty('li:first-child').next();
  // →  returns the second `
  • ` of every list in the document traversty('li.allstarts').next('li', 1); // → returns the `nextSibling` of the `nextSibling` of the starting elements traversty('li:first-child').next('li'); // → returns all `
  • ` elements, except for the first-children of every lits in the document

  • previous([selector [, index = 0]])

    traversty(elements).previous() returns a new Traversty instance containing previousSibling elements according to the arguments provided.

    Exactly the same as next() except it works on previousSibling, so you move backwards amongst sibling elements.

    Examples

    traversty('li:nth-child(20)').previous();
      // →  returns 19th child of the every list in the document (where it exists)
    traversty('li.allstarts').previous('li', 1);
      // →  returns the `previousSibling` of the `previousSibling` of the starting element
    traversty('li:nth-child(20)').previous('.interesting');
      // →  returns all `
  • ` elements with class "interesting" up to the 19th child of every list // in the document where there are at least 20 children.

  • prev([selector [, index = 0]])

    traversty(elements).prev() is a simple alias for previous(), provided mainly for jQuery compatibility.


    up([selector [, index = 0]])

    traversty(elements).up() returns a new Traversty instance containing parentNode elements according to the arguments provided.

    Similar to next() and previous() except that it works on parentNodes and will continue all the up to the document root depending on what you're asking for.

    If no index or selector is given then you get just the `parentNode*s of the elements.

    If just an index is provided then you'll get the index+1 parentNodes of the element. i.e. index is 0-based, like arrays, 0 is parentNode and 1 is parentNode.parentNode, unless you provide a selector of course, in which case it'll skip over non-matching elements.

    If just a selector is provided then no index will be assumed, you'll get all matching ancestor elements.

    Examples

    traversty('li#start').up();
      // →  returns the `
      ` parent element traversty('li.allstarts').up('ul', 1); // → returns the grandparent `
        ` elements if the start elements are nested at two levels traversty('li.allstarts').up('ul'); // → returns all ancestor `
          ` elements, no matter how deep the nesting

    parents([selector = '*' [, index ]])

    traversty(elements).parents() returns a new Traversty instance containing parentNode elements according to the arguments provided, similar, but not identical to up().

    Performs exactly the same as up(), except, the 'selector' argument defaults to '*' which has the effect of matching all ancestor elements, not just the first one. parents() will return exactly the same collection as up('*'). Provided mainly for jQuery compatibility.


    closest([selector = '*' [, index = 0]])

    traversty(elements).closest() returns a new Traversty instance containing the elements and/or parentNode elements according to the arguments provided, similar, but not identical to parents().

    Performs exactly the same operation as parents() except for two important differences:


    down([selector [, index = 0]])

    traversty(elements).down() returns a new Traversty instance containing descendant elements according to the arguments provided.

    While down() is very similar to the other methods, it's perhaps best to think of it as what you might get with a find() method from a selector engine.

    down() works on elements in document-order, so it operates on child elements and children of children but it also moves through child-siblings on the way to children of children.

    The following fragment should illustrate the indexing you get when you use down():

    • first
    • second
    • third
      • i
      • ii
      • iii
    • fourth

    So

    traversty('#root').down(5)
      // →  will give you `
  • ii
  • ` traversty('#root').down('li', 5) // → will give you `
  • i
  • ` because the `
      ` is ignored

    Of course down() works on multiple elements simultaneously just like the other methods.


    children([selector [, index = 0]])

    traversty(elements).children() returns a new Traversty instance containing direct descendant (child) elements according to the arguments provided.

    • first
      • i
      • ii
        • a
        • b
      • iii
      • iv
    • second
    traversty('#root > li').children()
      // →  will give you *only* the second level `
      ` element as it's // the only direct descendant of the top `
    • ` elements traversty('#root > li').children().children() // → will give you *only* the second level `
    • ` elements and none // of their children

    siblings([selector [, index = 0]])

    traversty(elements).siblings() returns a new Traversty instance containing previousSibling and nextSibling elements according to the arguments provided. It's important to note that the resulting collection will not include the original elements unless they are siblings of each other. To illustrate:

    • first
    • second
    • third
    • fourth
    traversty('#root :nth-child(2)').siblings()
      // →  will give you all `
  • ` elements except the second traversty('#root :nth-child(2n)').siblings() // → will give you all `
  • ` elements because they are all siblings of // the original collection's elements
  • siblings() is the only method in Traversty that is not guaranteed to return a collection of elements in document-order (i.e. in the order they appear in the HTML). If you call siblings() on elements that are already siblings then the collection mechanism may mean that the results are out of order. Generally this shouldn't matter but you are warned if order matters to you for some reason.


    first()

    traversty(elements).first() returns a new Traversty instance containing only the first element in the original collection.


    last()

    traversty(elements).last() returns a new Traversty instance containing only the last element in the original collection.


    eq(index)

    traversty(elements).eq() returns a new Traversty instance containing only the element at the index specified.

    Indexes are zero-based and can also be negative. A negative index will count backwards from the end of the collection.

    • first
    • second
    • third
    • fourth
    traversty('#root li').eq(1)
      // →  will give you `
  • second
  • ` traversty('#root li').eq(-2) // → will give you `
  • third
  • `

    slice(start [, end])

    traversty(elements).slice() returns a new Traversty instance containing only the elements between the start and end indexes. The end is optional, if left out then elements from start to the end of the collection are included.

    Indexes are zero-based and can also be negative. A negative index will count backwards from the end of the collection. See the example above for eq() for how this works.


    filter(selector | function | element)

    traversty(elements).filter() returns a new Traversty instance containing only the elements that satisfy the filter condition.

    A selector string argument will simply check each element against the selector and return only elements that match.

    A function argument will execute that function for each element in the collection and return only elements for which it receives a truthy response from the function. this within the function will be the element being checked and the single argument to the function will be the index within the collection.

    An element argument will return a collection containing only that DOM element *only if * it exists within the collection.

    • first
      • i
      • ii
        • a
        • b
      • iii
      • iv
    • second
    var els = traversty('#root *')
      // →  start off with all 12 descendant elements under #root
    els = els.filter('li')
      // →  returns only the 8 `
  • ` elements within the collection els = els.filter(function () { return /^i/.test(this.innerHTML) }) // → returns only the 3 `
  • ` elements start have content starting with 'i' // i.e. only 'ii', 'iii' and 'iv' (not 'i') els = els.filter(traversty('#root ul > li')[1]) // → we're using `traversty()` here as a simple selector to fetch the 'iii' element // which we pass in to `filter()`. Because this element is in the collection we get // back a collection with only this element.

  • not(selector | function | element)

    traversty(elements).not() returns a new Traversty instance containing only the elements that do not satisfy the filter condition.

    not() is the exact inverse of filter(), it takes the same arguments but returns only elements that don't match your conditions.


    has(selector | element)

    traversty(elements).has() returns a new Traversty instance containing only the elements that have descendant elements that match the provided selector argument, or have element as a descendant element.

    If a selector string argument is provided, each element in the collection effectively has a find(selector)-type operation performed on it, if any matching descendant elements are found, the parent element is retained for the new collection; otherwise it is not included.

    If an element argument is provided then the only element included in the resulting collection is an ancestor of that element, if the element is not a descendant of any of the elements in the collection then the resulting collection will be empty.

    • first
      • i
      • ii
        • a
        • b
      • iii
      • iv
    • second
    var els = traversty('#root *')
      // →  start off with all 12 descendant elements under #root
    els = els.has('li')
      // →  returns a collection of 4 elements which have `
  • ` descendants: the 'first' `
  • `, // the `

  • is(selector | function | element)

    traversty(elements).is() returns a boolean indicating whether at least one of the elements within the collection matches the condition. The method should be thought of as a version of filter() that returns a boolean if the resulting collection has at least one element; i.e. traversty(elements).filter(condition).length > 0.


    each(function [, thisContext])

    traversty(elements).each() will execute the provided function on each of the elements in the current collection. each() will return the original collection so you can continue chaining method calls.

    Your function will be called with this equal to the individual elements or the thisContext argument if supplied. The arguments provided to the function are:

    1. element: the current element in the collection
    2. index: the index of the current element in the collection
    3. collection: the entire Traversty object for this collection

    Note the ordering of arguments 1 and 2 are different to the jQuery().each(), instead Traversty is closer to ES5 Array.prototype.forEach.

    traversty('li').each(function (el, i) {
      this.innerHTML += ' (I am ' + i + ')'
    })
    

    get(index)

    traversty(elements).get() returns a single DOM element at the specified index of the collection. Indexes are zero-based and can be negative. See eq() for specifics.


    toArray()

    traversty(elements).toArray() returns a true Array object containing elements within the collection. See MDN for details on what you get.


    size()

    traversty(elements).size() returns an number indicating the number of elements in the collection. Works exactly the same as .length on an Array (indeed, you can call .length on a Traversty object and get the same value).


    push(element1 [, element2 [...]])

    traversty(elements).push() reuses Array.prototype.push. See MDN for details.

    Beware of pushing non-DOM elements onto a Traversty object! This is not supported behaviour.


    sort([compareFunction])

    traversty(elements).sort() reuses Array.prototype.sort to sort the collection. See MDN for details.


    splice(index, howMany [, element1 [...]])

    traversty(elements).splice() reuses Array.prototype.splice to splice the collection. See MDN for details.


    aug(methodMap)

    traversty.aug() extends Traversty's functionality with custom methods off the main Traversty prototype. The methodMap is simply a map of method names to functions. The functions will respond when called off a collection: traversty().method(args).

    traversty.aug({ append: function (element) {
      // make sure we return 'this', which we can get from each()
      return this.each(function (el, i) {
        // append original to first element, append a clone to the rest
        el.appendChild(i > 0 ? element.cloneNode(true) : element)
      })
    }})
    
    var span = document.createElement('span')
    span.innerHTML = 'BOOM!'
    traversty('li').append(span)
    

    setSelectorEngine(selectorEngine)

    traversty.setSelectorEngine() injects a selector engine for Traversty to use. See the next section for details. Returns the main Traversty object for chainability, e.g.: var $ = traversty.setSelectorEngine(qwery).

    Selector engines

    Traversty should work out-of-the-box on modern browsers as it leverages native querySelectorAll() and matchesSelector() where they exist. This means that you should be able to use Traversty without a selector engine on most smartphone browsers without any problems.

    Unfortunately, this doesn't work with older browsers, particularly IE8 and below. While IE8 has a CSS2-compliant querySelectorAll(), it doesn't have a matchesSelector() which Traversty makes heavy use of.

    Traversty allows you to plug in your favourite selector engine so it can work on whatever browsers your engine supports. Traversty is tested to support Qwery, Sel, Sizzle, NWMatcher and Zest.

    Traversty uses feature detection to figure out how to use your selector engine, it tries to find the method used to find elements given a element root and the method used to determine if an element matches a given selector. If it can't figure out how to use your selector engine then you just need to pretend that it works like one of the supported ones and it should be OK.

    For example:

    traversty.setSelectorEngine({
        select: function(selector, root) {
          return MyEngine(selector, root);
        }
      , is: function(selector, root) {
          return MyEngine(root).isTheSameAs(selector);
        }
    });
    

    Traversty will also do some trickery to make up for deficiencies in some selector engines, such as out-of-order results when selecting on groups ('a,b').

    If you have a new selector engine that you want Traversty to support then either let me know or fork, patch and submit.

    I want a demo!

    You'll have to make do with the integration tests:

    Ender

    Here is Traversty running in an Ender build with Qwery and Bonzo. You can also see it running with Sel, Sizzle, NWMatcher and without a selector engine (works in modern browsers, including IE9+).

    View-source to see what it's doing, note that it's operating on 2 lists at the same time.

    Vanilla

    Here is Traversty bundled with Qwery as the selector engine and the css() augmenting example code /examples/aug-css.js performing the same integration tests. There is also the same example using Zest instead here

    Things to note

    Supported browsers

    Traversty is tested with IE6+, Firefox 3+, Safari 4+, Opera current and Chrome current. You'll need a supported selector engine to operate on some of these older browsers.

    Ender integration

    Traversty is designed to be inserted into an Ender build. It's in npm so simply include it in your build command, something like: ender build sel bonzo traversty

    Traversty will attempt to use whatever selector engine you've included in your Ender build.

    What about Bonzo?

    Traversty is designed to add to the goodness you get in Bonzo, although Bonzo isn't a dependency. Bonzo has next() and previous() and a few other methods already and it is intended that Traversty replace these in your Ender build (because they are way-better!). Argument-less they should do exactly the same thing but Traversty adds the extra arguments for greater flexibility. If you are using Bonzo in Ender along with Traversty then you should make sure Traversty is included after Bonzo. Unfortunately, Ender doesn't guarantee order so you may have to fiddle a bit. The Ender 1.0 CLI does correct ordering but that's not formally released yet, you can use it by installing ender via npm with npm install ender@dev.

    Contributing

    Awesome! Just do it, fork and submit your pull requests and they will be promptly considered.

    I'd also love it if you could contribute tests for bugs you find or features you add.

    Tests

    Traversty uses Buster for unit testing.

    Since Buster is still in Beta, the capture-server/client is a bit buggy and can be frustrating. So, instead, simply run index.html file in the tests directory in each of the browsers you need to test. It'll load and run all of the tests.

    Credits

    Licence

    Traversty is Copyright (c) 2012 Rod Vagg @rvagg and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.