Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

1302 lines (909 sloc) 25.962 kb

package: elements

In many examples below you will see require() calls, as if elements was used in nodejs. You can build elements for browsers with any commonJS build tool, such as WrapUp or Browserify.

var $ = require('elements')

// elements utilities
var ready = require('elements/domready')
var zen = require('elements/zen')

// and finally use the modules
ready(function(){
    var text = "When all else fails, read the manual"
    var element = zen('div.className').text(text).insert(document.body)
})

module: elements

exports

elements.js exports a function which returns an elements instance. The main module includes every other module used by elements, but you can choose to require('elements/base') if you only want the barebones.

Notes:

  1. an elements instance will never contain duplicate elements
  2. if the internal collection is empty, you will get null instead of an empty elements instance.

parameters

  1. (node / collection / string / array) - an dom node, a collection of nodes, a string representing a css selector (requires slick or any other selector engine) or an array containing any of the above.
  2. context - (node - optional, defaults to document) - when string is used as the first argument, the context argument will decide from where to run the dom search.

syntax

var $ = require('elements')

var elements = $(document.getElementsByTagName('div'))
elements.addClass('test')

var element = $(document.getElementById('myElement'))
element.addClass('test')

var elements = $('li.someClass')

// requires a selector engine
var elements = $(['li.someClass', someDiv, document.getElementsByTagName('a')])

var element = $(document.getElementById('not-existing')) // → null

selector engine integration

When requiring the base module, you can integrate any selector engine:

var $ = require('elements')
$.implement({
    search: function(expression){
        /*... filtering logic ...*/
    },
    sort: function(){
        /*... sorting logic ...*/
    }
})

The default selector engine is slick.

method: forEach

Calls a function for each element in the array.

syntax

elements.forEach(fn[, bind])

parameters

  1. fn - (function) Function to execute for each element. fn is called like fn(element, index) where element is the native element, and index is the index of the element in the elements collection.
  2. bind - (object, optional) Object to use as this when executing fn.

sample

var elements = $(document.getElementsByTagName('a'))
elements.forEach(function(element, index){
    return $(element).text('element: ' + index)
})

See also

method: map

Creates a new array with the results of calling a provided function on every element in the elements collection. Returns the new mapped array.

syntax

var mapped = elements.map(fn[, bind])

parameters

  1. fn - (function) Function that produces an element of the new Array from an element of the current one. fn is called like fn(element, index) where element is the native element, and index is the index of the element in the elements collection.
  2. bind - (object, optional) Object to use as this when executing fn.

sample

var elements = $(document.getElementsByTagName('a'))
var result = elements.map(function(element, index){
    return $(element).attribute('href')
}) // array with all href values of each element

See also

method: filter

Creates a new array with all of the elements of the collection for which the provided filtering function returns true. Returns an array with only the filtered elements

syntax

var filtered = elements.filter(fn[, bind])

parameters

  1. fn - (function) The function to test each element of the collection. fn is called like fn(element, index) where element is the native element, and index is the index of the element in the elements collection.
  2. bind - (object, optional) Object to use as this when executing fn.

sample

var elements = $(document.getElementsByTagName('*'))
var filtered = elements.filter(function(element, index){
    return element.childNodes.length > 4
}) // array with elements that have more than 4 direct children

See also

method: every

If every element in the collection satisfies the provided testing function, returns true. Otherwise, returns false.

syntax

var allPassed = elements.every(fn[, bind])

parameters

  1. fn - (function) The function to test each element of the collection. fn is called like fn(element, index) where element is the native element, and index is the index of the element in the elements collection.
  2. bind - (object, optional) Object to use as this when executing fn.

sample

var elements = $(document.getElementsByTagName('div'))
var allEnoughChildren = elements.every(function(element, index){
    return element.childNodes.length > 4
}) // true if each div has more than 4 child elements

See also

method: some

If some element in the collection satisfies the provided testing function, returns true. Otherwise, returns false.

syntax

var somePassed = elements.some(fn[, bind])

parameters

  1. fn - (function) The function to test each element of the collection. fn is called like fn(element, index) where element is the native element, and index is the index of the element in the elements collection.
  2. bind - (object, optional) Object to use as this when executing fn.

sample

var elements = $(document.getElementsByTagName('div'))
var someEnoughChildren = elements.some(function(element, index){
    return element.childNodes.length > 4
}) // true if some div has more than 4 child elements

See also

module: zen

The zen modules generates dom elements using CSS-Style selectors. Note: zen requires the slick parser.

exports

exports the function used to generate elements.

syntax

var zen = require('elements/zen')

// returns elements instance with one div element
zen('div')

// returns elements instance with two a elements
zen('a + a')

// returns an elements instance with an a in a div
zen('div a')

// returns an elements instance with one div element with an id, class, and
// href attributes
zen('div a#link.menu.big[href="test.html"]')

module: attributes

This the attributes module implements attribute-related methods to elements.

exports

elements

syntax

var $ = require('elements/attributes')

same as

var $ = require('elements')
require('elements/attributes')

method: attribute

Gets or sets an attribute or property. Returns the value of the attribute If only the name parameter is passed, otherwise returns the current elements instance.

syntax

element.attribute(name[, value])

parameters

  1. name (string) The name of the attribute or property
  2. value (string, optional) If the value parameter is set, this method will act like a setter and will set the value to all elements in the collection. If this parameter is omitted, it will act as a getter on the first element in the collection.

sample

<a href="/test" title="elements">test</a>
// as getter
element.attribute('title') // returns 'some title'
// as setter
element.attribute("text", "Here's Johnny!")
element.attribute("title", "The Shining")

convenience methods

There are several convenience methods available to work with attributes. Used as a setter, the methods will return the elements instance, while used as a getter, they will return a string value:

  • type
  • value
  • name
  • title
  • id

Used only as a getter, the following methods will return a boolean value:

  • checked
  • disabled
  • selected

The following methods will return the elements instance, and perform a self-explanatory action.

  • check
  • uncheck
  • disable
  • enable
  • select
  • deselect

method: classNames

Gets a sorted array of all class names of an element.

syntax

elements.classNames()

method: hasClass

Tests the element to see if it has the passed in className. Returns the boolean true, or false.

sample

var result = myElement.hasClass(className)

parameters

  1. className - (string) The class name to test.

sample

<div id="myElement" class="testClass"></div>
$(document.getElementById('myElement')).hasClass('testClass'); // returns true

method: addClass

Adds the passed in class to the element, if the element doesn't already have it. Returns the elements instance.

syntax

myElement.addClass(className)

parameters

  1. className - (string) The class name to add.

sample

<div id="myElement" class="testClass"></div>
$(document.getElementById('myElement')).addClass('newClass')
<div id="myElement" class="newClass testClass"></div>

method: removeClass

Works like addClass, but removes the class from the element. Returns the elements instance.

syntax

myElement.removeClass(className)

parameters

  1. className - (string) The class name to remove.

sample

<div id="myElement" class="testClass newClass"></div>
$(document.getElementById('myElement')).removeClass('newClass')
<div id="myElement" class="testClass"></div>

method: toggleClass

Removes or adds a class from the element, depending on if it's currently set or not. Returns true or false, depending on if the className was set.

Takes an optional second parameter to force the value on or off, useful to set a className based on a condition.

syntax

myElement.toggleClass(className[, forceState])

parameters

  1. className - (string) The class name to toggle.
  2. forceState - (mixed, optional) Parameter that, when present, enforces to add or remove className.

sample

<div id="myElement" class="testClass oneMore"></div>
$(document.getElementById('myElement')).toggleClass('testClass')
<div id="myElement" class="oneMore"></div>
var mustHaveClass = true;
$(document.getElementById('myElement')).toggleClass('otherClass', mustHaveClass)
<div id="myElement" class="oneMore otherClass"></div>

method: toString

Creates a simple CSS selector from the element.

sample

<div id="myElement" class="otherClass testClass"></div>
$(document.getElementById('myElement')).toString() // div#myElement.otherClass.testClass

method: tag

Gets the tag name of an element as a lower case string.

syntax

myElement.tag() // div

method: html

Set or get HTML of an element.

syntax

myElement.html([html])

parameters

  1. html - (string) If the html parameter is set, it will set the HTML in the element, otherwise it will return the current HTML in the element. Returns the elements instance If the html parameter is set, otherwise a string containing the HTML in the element.

sample

myElement.html('<p>new html</p>')
// or
var html = myElement.html() // returns: <p>new html</p>

method: text

Sets or gets the text of on element. Returns the elements instance when setting a value, otherwise a string containing the text in the element.

syntax

myElement.text([text])

parameters

  1. text - (string) If the text parameter is set, it will set the text in the element, otherwise it will return the current text in the element.

sample

myElement.text("I'm just contemplating the ifs.")
// or
var text = myElement.text()

module: domready

exports

Exports a function that executes functions passed to it when the DOM is loaded.

sample

var domready = require('elements/domready')
domready(function(){
    alert('The DOM is ready!')
})

module: events

The events.js module implements functions to attach event listeners to DOM elements on the page.

See also MDN DOM Event Reference.

exports

elements

method: on

Attaches an event listener to a DOM element. Returns the elements instance.

syntax

myElement.on(type, fn)

parameters

  1. type - (string) The event name to monitor ('click', 'load', etc) without the prefix 'on'.
  2. fn - (function) The function to execute.

sample

myElement.on('click', function(event){
    alert('clicked')
})

method: off

Removes the specified event listener from the elements collection. Returns the elements instance.

syntax

myElement.off(type, fn)

parameters

  1. type - (string) The event name.
  2. fn - (function) The function to remove.

sample

var destroy = function(){
    alert('Boom: ' + this.id)
} // this refers to the element.

myElement.on('click', destroy)

//later...
myElement.off('click', destroy)

method: emit

Executes all events attached for the specified type on an element. Returns the elements instance.

syntax

myElement.emit(type[, args...])

parameters

  1. type - (string) The event name.
  2. args... - (mixed, optional) Zero or multiple extra parameters that will be passed to the event listeners

sample

var add = function(a, b){
    alert(a + b)
}
element.on('click', add)
element.emit('click', 4, 2) // alerts 6

module: delegation

Delegation is a common practice where an event listener is attached to a parent element to monitor its children rather than attach events to every single child element. It's more efficient for dynamic content or highly interactive pages with a lot of DOM elements.

exports

elements

method: delegate

Add a new delegation event listener to an element. Returns the elements instance.

syntax

myElement.delegate(type, selector, fn)

parameters

  1. type - (string) The event name.
  2. selector - (string) A CSS Selector the element the event is fired on should match (see matches)
  3. fn - (function) The function to execute.

sample

<ul>
    <li><a href="#">one</a></li>
    <li><a href="#">two</a></li>
    <li><a href="#">three</a></li>
</ul>
var $ = require('elements/delegation')

$('ul').delegate('click', 'a', function(event, a){ // a is the matching element
    alert(a.text())
})

method: undelegate

Removes a delegation event listener from an element. Opposite operation of delegate. Returns the elements instance.

syntax

myElement.undelegate(type, selector, fn)

parameters

  1. type - (string) The event name.
  2. selector - (string) A CSS Selector the element the event is fired on should match (see matches).
  3. fn - (function) The function to remove.

sample

var click = function(event, a){
    alert(a.text())
}
// add the delegation listener
$('ul').delegate('click', 'a', click)
// later remove the delegation listener again
$('ul').undelegate('click', 'a', click)

module: insertion

Insertion implements methods to insert, remove or replace elements from / to the DOM.

exports

elements

sample

var $ = require('elements/insertion')

var vince = $(document.getElementById('vince'))
$(document.createElement('div')).insert(vince)

method: appendChild

Wrapper method of the native appendChild method. It will append another element as child element. Returns the elements instance.

syntax

parent.appendChild(child)

parameters

  1. child - (elements) another elements instance.

sample

<div id="child"></div>
<div id="parent"></div>
var parent = $(document.getElementById('parent'))
var child = $(document.getElementById('child'))
parent.appendChild(child)

Resulting HTML

<div id="parent"><div id="child"></div></div>

See also

method: insertBefore

Wrapper method of the native insertBefore method. It will insert an element before another element. Returns the elements instance.

syntax

parent.insertBeore(child, ref)

parameters

  1. child - (elements) The child elements instance.
  2. ref - (elements) The reference element. child will be inserted before ref.

sample

<div id="first"></div>
<div id="parent">
    <div id="second"></div>
</div>
var parent = $(document.getElementById('parent'))
var child = $(document.getElementById('first'))
var ref = $(document.getElementById('second'))
parent.insertBefore(child, ref)

Resulting HTML

<div id="parent">
    <div id="first"></div>
    <div id="second"></div>
</div>

method: removeChild

Wrapper method of the native removeChild method. It will remove a child element from the parent element. Returns the elements instance.

syntax

parent.removeChild(child)
  1. child - (elements) An elements instance, which is a child of the parent element.

sample

<div id="parent">
    <div id="child"></div>
</div>
var parent = $(document.getElementById('parent'))
var child = $(document.getElementById('child'))
parent.removeChild(child)

Resulting HTML

<div id="parent"></div>

method: replaceChild

Wrapper method of the native replaceChild method. It will replace one element with another. Returns the elements instance.

syntax

  1. child - (elements) The child elements instance.
  2. ref - (elements) The reference element. ref will be replaced with child.

sample

<div id="child"></div>
<div id="parent">
    <div id="ref"></div>
</div>
var parent = $(document.getElementById('parent'))
var child = $(document.getElementById('child'))
var ref = $(document.getElementById('ref'))
parent.replaceChild(child, ref)

Resulting HTML

<div id="parent"><div id="child"></div></div>

method: before

Inserts elements before an element. Returns the elements instance.

sample

myFirstElement.before(mySecondElement)

Resulting HTML

<div id="myFirstElement"></div>
<div id="mySecondElement"></div>

method: after

Inserts an element after another element.

sample

myFirstElement.after(mySecondElement)

Resulting HTML

<div id="mySecondElement"></div>
<div id="myFirstElement"></div>

method: bottom

Injects an element at the bottom of another element. Returns the elements instance.

sample

myFirstElement.bottom(mySecondElement)

Resulting HTML

<div id="mySecondElement">
    <div id="myThirdElement"></div>
    <div id="myFirstElement"></div>
</div>

method: top

Injects elements at the top of another element. Returns the elements instance.

sample

myFirstElement.top(mySecondElement)

Resulting HTML

<div id="mySecondElement">
    <div id="myFirstElement"></div>
    <div id="myThirdElement"></div>
</div>

method: insert

insert is an alias of bottom. Returns the elements instance.

method: remove

Removes one or more elements from the DOM.

<div id="myElement"></div>
<div id="mySecondElement"></div>
$(document.getElementById('myElement')).remove()
<div id="myElement"></div>

method: replace

Replace another element with this element. Returns the elements instance.

sample

myNewElement.replaces(myOldElement)
// myOldElement is gone, and myNewElement is in its place.

module: traversal

Adds multiple methods for finding other elements.

sample

var $ = require('elements/traversal')

Note

  • Using the traversal package will require the slick package.

See also

method: search

Search elements with by an selector, with the current elements as context. Returns a new elements instance if not empty, otherwise, null.

syntax

elements.search(expression)

parameters

  1. expression - (string) A CSS selector.

sample

// slick is included by traversal, we can pass selectors to $()
// select all p elements
var elements = $('p')
// select all a elements in the previously found p elements
elements.search('a')

See also

method: find

Find one element for each element in the elements collection. Returns a new elements instance with the found elements, otherwise null.

syntax

elements.find(expression)

parameters

  1. expression - (string) A CSS selector.

sample

<ul>
    <li>Rome</li>
    <li>Delft</li>
    <li>Graz</li>
</ul>
<ul>
    <li>Stockholm</li>
    <li>London</li>
</ul>
// We can pass selectors to $() because slick is included by traversal

// select both ul elements
var elements = $('ul')
// select the first element for each list
var cities = elements.find('li')
// cities now contains "Rome" and "Stockholm"

See also

method: matches

Test if this element matches the passed CSS Selector. If the element matched, returns true. Otherwise, returns false.

syntax

element.matches(selector)

parameters

  1. match - (string) a CSS selector to test this element against

sample

<div>
    <a class="moo" href="http://mootools.net">MooTools</a>
    <a class="goo" href="http://google.com">
</div>
var moo = $('a.moo')
moo.matches('a[href*="mootools"]') // true

var goo = $('a.goo')
goo.matches('a[href*="mootools"]') // false

method: nextSiblings

Returns all next siblings of each element in the collection.

syntax

var nextSiblings = element.nextSiblings([expression])

parameters

  1. (string, optional) - A CSS Selector to filter the next siblings

sample

<section>
    <em></em>
    <p></p>
    <div></div>
    <p></p>
    <em></em>
    <p></p>
    <strong></strong>
</section>
<section>
    <a></a>
    <div></div>
    <strong></strong>
    <p></p>
    <em></em>
</section>
var div = $('div') // finds the two div elements
div.nextSiblings() // returns [p, em, p, strong, strong, p, em]
div.nextSiblings('p') // returns [p, p, p]

method: nextSibling

Exactly like nextSiblings, except it only returns the first next sibling that matches the expression, if any is given.

sample

With the same HTML as nextSiblings:

var div = $('div') // finds the two div elements
div.nextSibling() // returns [p, strong]
div.nextSibling('p') // returns [p, p]

method: previousSiblings

Exactly like nextSiblings, except it will return all previous siblings instead of next siblings, if any is given.

method: previousSibling

Exactly like nextSibling, except it will return one previous sibling instead of one next sibling, if any is given.

sample

With the same HTML as nextSibling:

var div = $('div') // finds the two div elements
div.previousSiblings() // returns [em, p, a]
div.previousSiblings('p') // returns [p]

method: children

Like nextSiblings, but returns the direct child elements, if they match the passed CSS expression, if any is given.

sample

With the same html as nextsiblings:

var div = $('div') // finds the two div elements
div.nextSibling() // returns [p, strong]
div.nextSibling('p') // returns [p, p]

method: parent

Get the parent node that matches the expression, if any given, for each element. Syntax is the same as nextSiblings.

sample

<div>
    <p>
        <strong></strong>
    </p>
</div>
var strong = $('strong') // finds the strong element
strong.parent() // the p element
strong.parent('div') // the div element

method: parents

Like parent(), but selects all parent elements that match the expression, if any given.

sample

With the same html as parent:

var strong = $('strong') // finds the strong element
strong.parents() // returns [p, div]
strong.parents('div') // only [div]
Jump to Line
Something went wrong with that request. Please try again.