form-cheatsheet/src/old/doc.js

88 lines
2.3 KiB
JavaScript

(this || window).doc = (function() {
"use strict";
var docProto = {
/**
* Create a proper JavaScript array from an array-like object
*
* @param {object} arrayLike
* @return {array}
*/
toArray: function(arrayLike) {
return [].slice.call(arrayLike);
},
/**
* Search for an HTML element by css selector
*
* @param {string} sel - The css selector
* @param {Element} [context] - An optional parent element to search from
* @return {Element}
*/
qs: function(sel, context) {
context = context || document;
return context.querySelector(sel);
},
/**
* Get an array of HTML elements by css selector
*
* @param {string} sel - The css selector
* @param {Element} [context] - An optional parent element to search from
* @return {Element[]}
*/
qsa: function(sel, context) {
context = context || document;
return this.toArray(context.querySelectorAll(sel));
},
/**
* Get an HTML element by its id attribute
*
* @param {string} id
* @param {Element} [context] - An optional parent element to search from
* @return {Element}
*/
getById: function(id, context) {
context = context || document;
return context.getElementById(id);
},
/**
* Get an array of HTML elements by their tag (element) name
*
* @param {string} tagName
* @param {Element} [context] - An optional parent element to search from
* @return {Element[]}
*/
getByTag: function(tagName, context) {
context = context || document;
return this.toArray(context.getElementsByTagName(tagName));
},
/**
* Get an array of HTML elements searching by a class
*
* @param {string} className
* @param {Element} [context] - An optional parent element to search from
* @return {Element[]}
*/
getByClass: function(className, context) {
context = context || document;
return this.toArray(context.getElementsByClassName(className));
},
/**
* Do multiple string replacements with a mapping array
*
* @param {string} str - The string to modify
* @param {string[][]} replacements - map [search, replacement]
* @return {string}
*/
replaceMultiple: function(str, replacements) {
var output = str;
replacements.forEach(function(pair) {
output = output.replace(pair[0], pair[1]);
});
return output;
}
};
return Object.create(docProto);
}());