Skip to content

Instantly share code, notes, and snippets.

@qmmr
Created January 18, 2013 16:17
Show Gist options
  • Save qmmr/4565701 to your computer and use it in GitHub Desktop.
Save qmmr/4565701 to your computer and use it in GitHub Desktop.
Simple DOM manipulation library. Build in progress...
;(function(window, undefined) {
'use strict';
var global = window;
var doc = global.document;
var regXContainsTag = /^\s*<(\w+|!)[^>]*>/;
var dom = function(params, context) {
return new GetOrCreateDom(params, context);
};
var GetOrCreateDom = function(params, context) {
var currentContext = doc;
if (context) {
currentContext = (context.nodeType) ? context : doc.querySelector(context);
}
if (!params || params === '' || typeof params == 'string' && params.trim() == '') {
this.length = 0;
return this;
}
if (typeof params == 'string' && regXContainsTag.test(params)) {
// HTML string, construct domFragment, fill object and return
var divElem = currentContext.createElement('div');
divElem.className = 'test-wrapper';
var docFrag = currentContext.createDocumentFragment();
docFrag.appendChild(divElem);
var queryDiv = docFrag.querySelector('div');
queryDiv.innerHTML = params;
var numChildren = queryDiv.children.length;
// loop over nodelist and fill object
// needs to be done because a string of html can be passed with siblings
for (var i = 0; i < numChildren; i += 1) {
this[i] = queryDiv.children[i];
}
// give the object a length value
this.length = numChildren;
// return object
return this; // e.g. {0:ELEMENT_NODE,1:ELEMENT_NODE,length: 2}
}
// if a single node reference is passed, fill object, return object
if (typeof params == 'object' && params.nodeName) {
this.length = 1;
this[0] = params;
return this;
}
// if it is an object but not a node, assume nodelist or array
// else it's a string selector, so create a nodelist
var nodes;
if (typeof params != 'string') {
// nodelist or array
nodes = params;
}
else {
// string
nodes = currentContext.querySelectorAll(params.trim());
}
// loop over array or nodelist created above and fill object
var nodeLength = nodes.length;
for (var j = 0; j < nodeLength; j += 1) {
this[j] = nodes[j];
}
// assign length
this.length = nodeLength;
return this;
};
global.dom = dom;
dom.fn = GetOrCreateDom.prototype;
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment