Doc-amd library
doc.js is a small library to manipulate the DOM in any browser. We focused on the most used and common use cases to create this. This library uses amd structure.
We needed a small footprint alternative for jquery and still have the ease-of-use for the most commonly used methods on it.
Then, we built it from scratch.
Install with Npm: npm install elo7-doc-amd
Doc-amd depends on an amd implementation. We suggest define-async implementation for dependency lookup. Doc-amd also depends on events-amd.
doc(querySelector)
doc(HTMLCollection)
doc(NodeList)
doc(Array)
doc(Node)
Returns a Doc object with all the methods below.
querySelector: String //A CSS selector. Note that, if it is a class name with dots, the dots must be escaped. E.g.: doc(".my\.class")
define(['doc'], function(doc) {
doc('.link')
doc('#link')
doc('a')
doc('li > a')
doc(document.body.children)
doc(document.body.childNodes)
doc(document.body)
doc([document.head, document.body])
});
.els()
Returns an array with matched Elements.
define(['doc'], function(doc) {
doc('a').els
doc('li .links').els[1]
});
.size
Returns the length of elements.
define(['doc'], function(doc) {
var numberOfElements = doc('a').size;
});
.each(callback)
Iterate through a Doc object, executing a Function on each one of them.
callback: Function() //A function to call.
define(['doc'], function(doc) {
doc('a').each(function(el){
console.log(el) //DOM Element
});
});
.data(key [,value])
Get or set the value of a data-* attribute
key: String //A string naming the piece of data to set or get.
value: String //The new data value.
define(['doc'], function(doc) {
doc('a.link').data('bar'); //Get the value of the attribute data-bar
doc('a.link').data('foo','test'); //Set the value of the attribute data-foo
});
.val([value])
Get or set the value of the element
value: String //The new value.
define(['doc'], function(doc) {
doc('input[name=email]').val(); //Get the value of the element
doc('input[name=email]').val('[email protected]'); //Set the value of the element
});
.html([value])
Get or set the value of the inner html
value: String //The new value.
define(['doc'], function(doc) {
doc('div.content').html(); //Get the inner html of the element
doc('section').html('<p>Lorem ipsum sit amet in dollor, consecteur</p>'); //Set the inner html of the element
});
.prepend(element)
Prepends the existing DOM element, doc-amd element or text as child of the Doc object
element: Element //The element you want to prepend as a child of your selector.
define(['doc'], function(doc) {
var div = document.createElement('div');
doc('body').prepend(div); //Prepend the new DOM element as child of the Doc object
doc('body').prepend($('div.content')); //Prepend the exist DOM element as child of the Doc object
doc('body').prepend('<p>Text here</p>'); //Prepend text HTML as child of the Doc object
});
.append(element)
Append the DOM element as child of the Doc object
element: Element //The element you want to append as a child of your selector.
define(['doc'], function(doc) {
var div = document.createElement('div');
doc('body').append(div); //Append the new DOM element as child of the Doc object
doc('body').append($('div.content').first()); //Append the exist DOM element as child of the Doc object
});
.text(value)
Set the inner text of the element
value: String //New value for the text of the element.
define(['doc'], function(doc) {
doc('.content').text('Lorem ipsum'); //Set the inner text of the element
});
.attr(key [,value])
or .attr(object)
Get or set the value of the attribute
key: String //A string naming the attribute to set or get. value: String //The new value of the attribute.
or
value: Object //A javascript object
define(['doc'], function(doc) {
doc('input[name=email]').attr('disabled'); //Get the value of attribute
doc('input[name=email]').attr('type','password'); //Set the value of attribute
doc('input[name=email]').attr({'required': true, 'maxlength': 5}); //Set each index and value from object
});
.hasClass(class)
Verify if the Doc object has the CSS class
class: String //The CSS class of the element. Return boolean.
<div class='container'>Lorem</div>
define(['doc'], function(doc) {
doc('div').hasClass('container'); //Returns true
doc('div').hasClass('content'); //Returns false
});
.addClass(class)
Adds a CSS class to the element.
class: String //The CSS class of the element.
define(['doc'], function(doc) {
doc('div').addClass('content'); //Adds .content class to all divs
doc('div').addClass('hide active'); //Adds .hide and .active class to all divs
});
.removeClass(class)
Removes the CSS class from the element.
class: String //The CSS class of the element.
define(['doc'], function(doc) {
doc('div').removeClass('content'); //Removes .content class from all divs
doc('div').removeClass('hide active'); //Removes .hide and .active class from all divs
});
.toggleClass(class)
Adds or removes the CSS class from the element.
class: String //The CSS class you want to add or remove.
define(['doc'], function(doc) {
doc('div').toggleClass('content'); //Adds or remove .content class from all divs
doc('div').toggleClass('hide active'); //Adds or remove .hide and .active class from all divs
});
.removeItem()
Remove the element from the DOM.
define(['doc'], function(doc) {
doc('#box').removeItem(); //Remove the element from the DOM.
});
.find(querySelector)
Get the descendants of the Doc object, filtered by querySelector.
querySelector: String //Returns the query's matched elements.
<form>
<fieldset>
<input name='name' />
<input name='email' />
</fieldset>
</form>
define(['doc'], function(doc) {
doc('form').find('input[name=email]'); //Returns the Doc object input
doc('form').find('input'); //Returns the Doc object (containing all input elements)
});
.closest(querySelector)
Get the first ascendant of the Doc object, filtered by querySelector.
querySelector: String //Should not be a composite. e.g. "#id .class" or "tag.class" due to compatibility issues. Prefer simple selectors. e.g. '.class'. Returns the query's matched elements.
<form>
<fieldset>
<input name='name' />
<input name='email' />
</fieldset>
</form>
define(['doc'], function(doc) {
doc('input').closest('form'); //Returns the Doc object form.
});
.filter(attribute || callback)
There are two use cases for this method. If you use an attribute, it will return a Doc object containing all elements containing the attribute. If you use callback, filter() will test each element in the set against your callback and return boolean for each. The result will be a Doc object matching your Function.
attribute: String //A string containing an attribute to match the current set of elements against.
callback: Function() //A function used as a test for each element in the set. This is the current DOM element.
define(['doc'], function(doc) {
var requiredInputs = doc('form input').filter('required'); //Returns all inputs with required attribute
var requiredClassInputs = doc('form input').filter(function(element){
return element.hasClass('required');
}); //Returns all inputs with required class
});
.first()
Returns the first DOM element from the query list.
define(['doc'], function(doc) {
doc('div').first(); //Returns the first DOM element from the query list
});
.last()
Returns the last DOM element from the query list.
define(['doc'], function(doc) {
doc('div').last(); //Returns the last DOM element from the query list
});
.previous()
Returns the query's previous Doc object.
<form>
<fieldset>
<input name='name' />
<input name='email' />
</fieldset>
</form>
define(['doc'], function(doc) {
doc('input[name=email]').previous() //Returns the previous Doc object === input[name=name]
doc('input[name=name]').previous() //Returns the previous Doc object === undefined
});
.next()
Returns the query's next Doc object.
<form>
<fieldset>
<input name='name' />
<input name='email' />
</fieldset>
</form>
define(['doc'], function(doc) {
doc('input[name=name]').next() //Returns the next Doc object === input[name=email]
doc('input[name=email]').next() //Returns the next Doc object === undefined
});
.parent()
Returns the query's parent element.
<form>
<fieldset>
<input name='email' />
</fieldset>
</form>
define(['doc'], function(doc) {
doc('input[name=email]').parent(); //Returns the Doc object fieldset
doc('input[name=email]').parent().parent(); //Returns the Doc object form
});
This method is deprecated. Use the method isPresent()
instead.
Verifies if the element exists on the DOM. Returns boolean.
define(['doc'], function(doc) {
doc('artile#content').isPresent(); //Return true/false if the element exist
});
.checked(value)
Set or verify the checkbox or radio field checked state.
value: boolean //To indicate whether the element should be checked or not
define(['doc'], function(doc) {
doc('input[type=checkbox]').checked(); //Get checked state
doc('input[type=checkbox]').checked(true); //Set checked state
});
.on(event, callback [,eventCategory])
or
.on(event, callback [, { named: eventCategory, passive: passive } ])
Adds an event listener on a Doc object.
event: String //One or more events that you want to attach to your selector
callback: Function() //A function to call when the event is triggered
eventCategory: String //You can add multiple 'events' of the same type (e.g: click) and use the eventCategory parameter to remove certain events when needed. Use .off() to remove the attached handler.
passive: Boolean // If true, indicates that the function specified by listener will never call preventDefault()
Please note that this method does not work like jquery's .on(). If you append new elements in the page you will have to call .on again on those elements.
define(['doc'], function(doc) {
doc('button').on('click', function(){ ... }); //Adds an event listener for the 'click' event
doc('button').on('click mousemove', function(){ ... }); //Adds event listeners for the 'click' and 'mousemove' event
doc('button').on('click', function() { ... }, 'tracker'); //Adds a 'click' event listener with the 'tracker' eventCategory
doc('button').on('click', function() { ... }, { named: 'tracker', passive: true }); //Adds a 'click' event listener with the 'tracker' eventCategory that never call preventDefault()
});
.throttle(event, callback [,timeout] [,eventCategory])
Prevents a function from being called multiple times on a set amount of time. Useful to prevent multiple requests.
event: String //The event you want to
callback: Function() //The function to be called
timeout: Number //The time in ms you want the application to prevent multiple calls from being made. Default value is 1000.
eventCategory: You can add multiple 'events' of the same type (e.g: click) and use the eventCategory parameter to prevent one event from being called.
define(['doc'], function(doc) {
doc('button').throttle('click', function(){ ... }); //Adds an event listener for the 'click' event.
doc('button').throttle('click', function(){ ... }, 5000); //Adds an event listener for the 'click' event, preventing other 'click' events to fire within 5 seconds
doc('button').throttle('click', function(){ ... }, 1000, 'tracker'); //Adds an event listener for the 'click' event with 'tracker' category, aditional clicks will be ignored for 1 second.
});
.debounce(event, callback [,timeout] [,eventCategory])
Prevents a function from being called multiple times before a defined amount of time. Useful to prevent multiple requests.
event: String //The event you want to
callback: Function() //The function to be called
timeout: Number //The time in ms you want the application to prevent multiple calls from being made. Default value is 1000.
eventCategory: You can add multiple 'events' of the same type (e.g: click) and use the eventCategory parameter to prevent one event from being called.
define(['doc'], function(doc) {
doc('button').debounce('click', function(){ ... }); //Adds an event listener for the 'click' event.
doc('button').debounce('click', function(){ ... }, 5000); //Adds an event listener for the 'click' event, preventing 'click' events to fire before 5 seconds
doc('button').debounce('click', function(){ ... }, 1000, 'tracker'); //Adds an event listener for the 'click' event with 'tracker' category, preventing the listener to be called before 1 second.
});
.off(event [,eventCategory])
Removes the event listener from the Doc object.
event: String //The event you want to remove from your selector
eventCategory: String //Removes the attached handler of this category. See .on() for details.
define(['doc'], function(doc) {
doc('button').off('click'); //Removes the event listener
doc('button').off('click', 'tracker'); //Removes the event listener with the 'tracker' eventCategory
});
.trigger(event [, data])
Dispatches an event that can be listened using on()
.
event: String //The event you want to trigger for your selector
data: Additional data for custom triggered events
define(['doc'], function(doc) {
doc('button').trigger('click'); //Triggers the event click for button.
});
define(['doc'], function(doc) {
doc('button').on('customEvent', function(e) {
console.log(e.detail.additionalData);
});
doc('button').trigger('customEvent', { additionalData: "data"}); //Triggers the event click for button.
});
.selectedText()
Returns the selected text on a given input field.
define(['doc'], function(doc) {
doc('input[name=name]').selectedText() //Returns the selected text of the element.
});
.focus()
Focus the first matched element
define(['doc'], function(doc) {
doc('input[name=name]').focus() //Focus the first input named "name"
});
.removeAttr(attrName)
Removes the attribute from the element.
attrName: String //The name of the element's attribute.
define(['doc'], function(doc) {
doc('div').removeAttr('style'); //Removes style attribute from all divs
doc('a').removeAttr('href target'); //Removes href and target attribute from all a elements
});
.scrollIntoView([options])
Makes the first element matched by Doc visible at the top of the viewport.
options: boolean //To indicate whether the element should be aligned to the top of the visible area (default) or to the bottom object //An object with the properties block ("start" or "end", indicating the same as the boolean version above) and behavior ("auto" or "instant" or "smooth")
define(['doc'], function(doc) {
doc('div').scrollIntoView(); //Scroll until the first matched div appears at the top of the viewport
});
doc.broadcast(event [, data])
note: WITHOUT selector
Dispatches a global event that can be listened using on()
by multiple elements.
If you wish to use this function in IE8, you need to use the indexOf
polyfill for arrays before usage.
Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});
event: String //The event you want to trigger globally
data: Additional data for custom triggered events
define(['doc'], function(doc) {
doc('button').on('click', function(e) {
console.log(e.detail.param);
});
doc('body').on('click', function(e) {
console.log(e.detail.param);
});
doc.broadcast('click', { param: "I am listening"}); //Triggers the event click for everybody that listens for the 'onclick' event.
});
.insertBefore()
Inserts an element before each matched element
define(['doc'], function(doc) {
doc('#some-element').insertBefore('a'); //Inserts the element with id some-element before each <a> element
var elements = doc('.before-me');
doc('#some-element').insertBefore(elements); //Inserts the element with id some-element before elements previously selected with doc-amd
});
.insertAfter()
Inserts an element after each matched element
define(['doc'], function(doc) {
doc('#some-element').insertAfter("a"); //Inserts the element with id some-element after each <a> element
var elements = doc('.after-me');
doc('#some-element').insertAfter(elements); //Inserts the element with id some-element after elements previously selected with doc-amd
});
Script | Description |
---|---|
npm start |
Start the server. |
npm run start:dev |
Run the start script and then the watch script. |
npm run test |
Run test locally. |
npm run test:ci |
Run the server and the tests. Useful for a quick local check and for CI environment. |
Doc-amd is released under the BSD. Have at it.
Copyright ©️ 2015 Elo7# doc-amd