Who is online?
In total there is 1 user online :: 0 Registered, 0 Hidden and 1 Guest

None

[ View the whole list ]


Most users ever online was 9 on Sun Jul 09, 2017 2:04 am
Statistics
We have 15 registered users
The newest registered user is bilde

Our users have posted a total of 271 messages in 27 subjects
deleted after updated

handy functions

View previous topic View next topic Go down

handy functions

Post by Admin on Fri Mar 30, 2012 10:15 am

Code:

(function(doc) {
   Document.prototype.byId = function(id) {
      return document.getElementById(id)
   };
   
   if (!'indexOf' in Array) {
      Array.prototype.indexOf = function(obj) {
         for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === obj) return i;
         }
         return -1;
      };
   }
   
   String.prototype.documentFragment = function() {
      if (document.createContextualFragment) {
         return document.createRange().createContextualFragment(this);
      }
      else {
         var container = document.createDocumentFragment(), div = document.createElement('div'), cur;
         div.innerHTML = this;
         while (cur = div.firstChild) {
            container.appendChild(cur);
         }
         return container;
      }
   };
   
   var ep = Element.prototype;
   
   ep.isWithin = function(parent) {
      if ('contains' in ep) {
         return parent.contains(this);
      }
      else {
         var p = this;
         while (p = p.parentNode) {
            if (p === parent) {
               return true;
            }
         }
         return false;
      }
   };
   
   ep.byTag = function(tag) {
      return this.getElementsByTagName(tag)
   };
   
   doc.byTag = ep.byTag;
   
   ep.byName = function(name) {
      var arr = document.getElementsByName(name), ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         //if this node of wanted name is within the context node.
         if(arr[i].isWithin(this)) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byName = ep.byName;
   
   ep.byClass = function(classname,tag) {
      return 'getElementsByClassName' in doc ?
         this.getElementsByClassName(classname) :
         (function(t){
            if(!tag) tag = '*';
            var arr = t.getElementsByTagName(tag), ret = [];
            for(var i=0,l=arr.length; i<l; i++) {
               var classes = arr[i].className.split(' ');
               if(classes.indexOf(classname) != -1) {
                  ret.push(arr[i]);
               }
            }
            return ret;
         })(this);
   };
   
   doc.byClass = ep.byClass;
   
   ep.byAttr = function(attr,value) {
      var ret = [], arr=this.getElementsByTagName('*');
      for (var i=0,l=arr.length; i<l; i++) {
         var a=arr[i].getAttribute(attr), add = 0;
         //add is bool whether or not we will add this elem to ret.
         if (a) {
            if(value) {
               //if elem has attr and a value is specified.
               add = a===value ? 1 : 0;
               //if its attr equals the wanted value then make add true. Else leave it false, we don't want it.
            }
            else {
               //the elem has the attribute, and no value is wanted, so we're going to add it.
               add = 1;
            }
         }         
         if(add) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byAttr = ep.byAttr;
   
   ep.byIndex = function(index) {
      return this.hasChildNodes() ? this.childNodes[index] : null;
   };
   
   doc.byIndex = ep.byIndex;
   
   ep.byNodeType = function(type) {
      var arr = this.childNodes, ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         if(arr[i].nodeType === type) ret.push(arr[i]);
         if(arr[i].hasChildNodes()) {
            ret = ret.concat(arr[i].byNodeType(type));
         }
      }
      return ret;
   };
   
   doc.byNodeType = ep.byNodeType;
   
   ep.byContent = function(str,tag) {
      if(!tag) tag = '*';
      var arr = this.getElementsByTagName(tag), ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         if(arr[i].innerHTML.indexOf(str) != -1) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byContent = ep.byContent;
   
   ep.prev = function() { return this.previousSibling }
   ep.next = function() { return this.nextSibling }
   ep.last = function() { return this.lastChild }
   ep.first = function() { return this.firstChild }
   
   ep.getText = function() {
      if('text' in ep) {
         return this.text;
      }
      else if('textContent' in ep) {
         return this.textContent;
      }
      else {
         var textNodes = this.byNodeType(3), str = '';
         for(var i=0,l=textNodes.length; i<l; i++) {
            str+=textNodes[i].nodeValue;
         }
         return str;
      }
   };
   
   ep.append = function(obj) {
      if(typeof obj == 'string') {
         this.appendChild( obj.documentFragment() );
      }
      else{
         this.appendChild(obj);
      }
      return this;
   };
   
   ep.prepend = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      if(this.firstChild) {
        this.insertBefore(obj,this.firstChild);
      }
      else {
        this.appendChild(obj);
      }
      return this;
   };
   
   ep.before = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      this.parentNode.insertbefore(obj,this);
      return this;
   };
   
   ep.after = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      if(this.nextSibling) {
         this.parentNode.insertBefore(obj,this.nextSibling);
      }
      else {
         this.parentNode.appendChild(obj);
      }
      return this;
   };
   
   ep.remove = function() {
      this.parentNode.removeChild(this);
   };
   
   ep.replaceWith = function(obj) {
      this.before(obj);
      this.remove();
   }
   
})(document);

having that in a page will allow for things like this:
document.byId('p156').byClass('postprofile')[0].byContent('LGforum')[0].append(' hello');

lol... a weird example.
But its really nothing new to learn. Its just getElementsByClassName/TagName/Id etc shortened, and also now byName byAttr and byNodeType and byContent are extra ones. Smile
avatar
Admin
Admin

Avacweb
Posts : 231
Points : 282
Join date : 2011-11-07

View user profile http://testlg.forumotion.co.uk

Back to top Go down

Re: handy functions

Post by Admin on Fri Mar 30, 2012 10:41 am


- byId
Function only for document use. 1 param ( string id of element ).
returns: element object.

- byTag
Function. 1 param ( string id of tagname )
returns: collection of nodes.

- byName
1 param (string name )
returns collection of nodes with matching name attribute

- byClass
1 param (string className )
returns: collection of nodes with matching classname.

- byAttr
2 params. ( string Attr name [, string attr value] )
returns: collection of nodes with attribute, with matching value if specified.

- byIndex
1 param (int Index )
returns: Element object at specified index.

- byNodeType
1 param ( int nodeType )
returns: collection of nodes of matching nodetype.

- byContent
1 param ( string content )
returns: collection of nodes that contain the specified string.

- prev
0 params.
returns: elements previous sibling.

- next
0 params.
returns: elements next sibling.

- first
0 params
returns: elements first sibling.

- last
0 params.
returns: elements last sibling.

- getText
0 params.
returns: all text content of element.

- append, appends markup or object to element.
1 param. ( string/element to append )
returns the element again.

- prepend
same as append, but prepend.

- before
...

- after
..

- remove
removes the element.

- replaceWith , replaces element with new markup or element.
1 param (string/element);
avatar
Admin
Admin

Avacweb
Posts : 231
Points : 282
Join date : 2011-11-07

View user profile http://testlg.forumotion.co.uk

Back to top Go down

Re: handy functions

Post by Admin on Sun Apr 01, 2012 12:04 pm

- added functions hide,show and toggle.
Obvious what they do.

Code:
(function(doc) {
   //new shorthand getElementById method.
   Document.prototype.byId = function(id) {
      return document.getElementById(id)
   };
   
   //adding indexOf array method if not supported.
   if (!'indexOf' in Array) {
      Array.prototype.indexOf = function(obj) {
         for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === obj) return i;
         }
         return -1;
      };
   }
   
   //adding a new string method. Converts a string of markup into a document fragment.
   String.prototype.documentFragment = function() {
      if (document.createContextualFragment) {
         return document.createRange().createContextualFragment(this);
      }
      else {
         var container = document.createDocumentFragment(), div = document.createElement('div'), cur;
         div.innerHTML = this;
         while (cur = div.firstChild) {
            container.appendChild(cur);
         }
         return container;
      }
   };
   
   //functions will be added directly to Element Object Prototype.
   var ep = Element.prototype;
   
   //Internal (or External too I suppose) for determining if the node is within (a descendant of) a specified node.
   ep.isWithin = function(parent) {
      if ('contains' in ep) {
         return parent.contains(this);
      }
      else {
         var p = this;
         while (p = p.parentNode) {
            if (p === parent) {
               return true;
            }
         }
         return false;
      }
   };
   
   ep.byTag = function(tag) {
      return this.getElementsByTagName(tag)
   };
   
   doc.byTag = ep.byTag;
   
   //returns node collection by name.
   ep.byName = function(name) {
      var arr = document.getElementsByName(name), ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         //if this node of wanted name is within the context node.
         if(arr[i].isWithin(this)) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byName = ep.byName;
   
   //returns node collection by className. Uses native if supported. Optional tag param for optmizing.
   ep.byClass = function(classname,tag) {
      return 'getElementsByClassName' in doc ?
         this.getElementsByClassName(classname) :
         (function(t){
            if(!tag) tag = '*';
            var arr = t.getElementsByTagName(tag), ret = [];
            for(var i=0,l=arr.length; i<l; i++) {
               var classes = arr[i].className.split(' ');
               if(classes.indexOf(classname) != -1) {
                  ret.push(arr[i]);
               }
            }
            return ret;
         })(this);
   };
   
   doc.byClass = ep.byClass;
   
   //get node collection by an attribute. If a value is specified only nodes with the attribute equalling the value will be returned.
   //eg byAttr('alt') - returns all elems with alt attribute. or byAttr('alt','hello') - returns all elems with alt='hello' attribute
   ep.byAttr = function(attr,value) {
      var ret = [], arr=this.getElementsByTagName('*');
      for (var i=0,l=arr.length; i<l; i++) {
         var a=arr[i].getAttribute(attr), add = 0;
         //add is bool whether or not we will add this elem to ret.
         if (a) {
            if(value) {
               //if elem has attr and a value is specified.
               add = a===value ? 1 : 0;
               //if its attr equals the wanted value then make add true. Else leave it false, we don't want it.
            }
            else {
               //the elem has the attribute, and no value is wanted, so we're going to add it.
               add = 1;
            }
         }         
         if(add) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byAttr = ep.byAttr;
   
   ep.byIndex = function(index) {
      return this.hasChildNodes() ? this.childNodes[index] : null;
   };
   
   doc.byIndex = ep.byIndex;
   
   //returns node collection by their node type. Can collect comment blocks or text nodes etc.
   ep.byNodeType = function(type) {
      var arr = this.childNodes, ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         if(arr[i].nodeType === type) ret.push(arr[i]);
         if(arr[i].hasChildNodes()) {
            ret = ret.concat(arr[i].byNodeType(type));
         }
      }
      return ret;
   };
   
   doc.byNodeType = ep.byNodeType;
   
   //returns node collection by their content. Specify a string, and if a node contains that string it will be returned.
   //optional tag param for optimizing.
   ep.byContent = function(str,tag) {
      if(!tag) tag = '*';
      var arr = this.getElementsByTagName(tag), ret = [];
      for(var i=0,l=arr.length; i<l; i++) {
         if(arr[i].innerHTML.indexOf(str) != -1) ret.push(arr[i]);
      }
      return ret;
   };
   
   doc.byContent = ep.byContent;
   
   //returns the text content of an elem as a string. Uses native if supported.
   ep.getText = function() {
      if('text' in ep) {
         return this.text;
      }
      else if('textContent' in ep) {
         return this.textContent;
      }
      else {
         var textNodes = this.byNodeType(3), str = '';
         for(var i=0,l=textNodes.length; i<l; i++) {
            str+=textNodes[i].nodeValue;
         }
         return str;
      }
   };
   
   //finds an element/s. Will return element with matching ID if any, or className or name. null if not found.
   ep.getElem = function(elem) {
      if(elem.nodeType && elem.nodeType == 1) return elem;
      if(document.byId(elem)) return document.byId(elem);
      if(this.byClass(elem)[0]) return this.byClass(elem);
      if(this.byName(elem)[0]) return this.byName(context);
      return null;
   };
   
   doc.getElem = ep.getElem;
   
   /* Pointless...
   ep.getElems(elem) = function(elem) {
      var ret = [];
      if(document.byId(elem)) ret.push(document.byId(elem));
      if(this.byClass(elem)[0]) ret = ret.concat(this.byClass(elem));
      if(this.byName(elem)[0]) ret = ret.concat(this.byName(context));
      return ret.length > 0 ? ret : null;
   }
   */
   
   ep.append = function(obj) {
      if(typeof obj == 'string') {
         this.appendChild( obj.documentFragment() );
      }
      else{
         this.appendChild(obj);
      }
      return this;
   };
   
   ep.prepend = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      if(this.firstChild) {
        this.insertBefore(obj,this.firstChild);
      }
      else {
        this.appendChild(obj);
      }
      return this;
   };
   
   ep.before = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      this.parentNode.insertbefore(obj,this);
      return this;
   };
   
   ep.after = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      if(this.nextSibling) {
         this.parentNode.insertBefore(obj,this.nextSibling);
      }
      else {
         this.parentNode.appendChild(obj);
      }
      return this;
   };
   
   ep.remove = function() {
      this.parentNode.removeChild(this);
   };
   
   ep.replaceWith = function(obj) {
      if(typeof obj == 'string') obj = obj.documentFragment();
      this.before(obj);
      this.remove();
      return obj;
   }
   
   ep.hide = function() {
      this.style.display = 'none';
      return this;
   };
   
   ep.show = function(display) {
      this.style.display = display ? display : '';
      return this;
   };
   
   ep.toggle = function(display) {
      if (this.style.display == 'none') {
         this.show(display);
      }
      else {
         this.hide();
      }
      return this;
   };
   
   
   
   
})(document);


Minified code:
Code:

(function(g){Document.prototype.byId=function(a){return document.getElementById(a)};!1 in Array&&(Array.prototype.indexOf=function(a){for(var d=0,c=arr.length;d<c;d++)if(arr[d]===a)return d;return-1});String.prototype.documentFragment=function(){if(document.createContextualFragment)return document.createRange().createContextualFragment(this);var a=document.createDocumentFragment(),d=document.createElement("div"),c;for(d.innerHTML=this;c=d.firstChild;)a.appendChild(c);return a};var b=Element.prototype; b.isWithin=function(a){if("contains"in b)return a.contains(this);for(var d=this;d=d.parentNode;)if(d===a)return true;return false};b.byTag=function(a){return this.getElementsByTagName(a)};g.byTag=b.byTag;b.byName=function(a){for(var a=document.getElementsByName(a),d=[],c=0,b=a.length;c<b;c++)a[c].isWithin(this)&&d.push(a[c]);return d};g.byName=b.byName;b.byClass=function(a,d){var c;if("getElementsByClassName"in g)c=this.getElementsByClassName(a);else{d||(d="*");c=this.getElementsByTagName(d);for(var b= [],e=0,j=c.length;e<j;e++)c[e].className.split(" ").indexOf(a)!=-1&&b.push(c[e]);c=b}return c};g.byClass=b.byClass;b.byAttr=function(a,b){for(var c=[],f=this.getElementsByTagName("*"),e=0,g=f.length;e<g;e++){var h=f[e].getAttribute(a),i=0;h&&(i=b?h===b?1:0:1);i&&c.push(f[e])}return c};g.byAttr=b.byAttr;b.byIndex=function(a){return this.hasChildNodes()?this.childNodes[a]:null};g.byIndex=b.byIndex;b.byNodeType=function(a){for(var b=this.childNodes,c=[],f=0,e=b.length;f<e;f++){b[f].nodeType===a&&c.push(b[f]); b[f].hasChildNodes()&&(c=c.concat(b[f].byNodeType(a)))}return c};g.byNodeType=b.byNodeType;b.byContent=function(a,b){b||(b="*");for(var c=this.getElementsByTagName(b),f=[],e=0,g=c.length;e<g;e++)c[e].innerHTML.indexOf(a)!=-1&&f.push(c[e]);return f};g.byContent=b.byContent;b.getText=function(){if("text"in b)return this.text;if("textContent"in b)return this.textContent;for(var a=this.byNodeType(3),d="",c=0,f=a.length;c<f;c++)d=d+a[c].nodeValue;return d};b.getElem=function(a){return a.nodeType&&a.nodeType== 1?a:document.byId(a)?document.byId(a):this.byClass(a)[0]?this.byClass(a):this.byName(a)[0]?this.byName(context):null};g.getElem=b.getElem;b.append=function(a){typeof a=="string"?this.appendChild(a.documentFragment()):this.appendChild(a);return this};b.prepend=function(a){typeof a=="string"&&(a=a.documentFragment());this.firstChild?this.insertBefore(a,this.firstChild):this.appendChild(a);return this};b.before=function(a){typeof a=="string"&&(a=a.documentFragment());this.parentNode.insertbefore(a,this); return this};b.after=function(a){typeof a=="string"&&(a=a.documentFragment());this.nextSibling?this.parentNode.insertBefore(a,this.nextSibling):this.parentNode.appendChild(a);return this};b.remove=function(){this.parentNode.removeChild(this)};b.replaceWith=function(a){typeof a=="string"&&(a=a.documentFragment());this.before(a);this.remove();return a};b.hide=function(){this.style.display="none";return this};b.show=function(a){this.style.display=a?a:"";return this};b.toggle=function(a){this.style.display== "none"?this.show(a):this.hide();return this}})(document);
avatar
Admin
Admin

Avacweb
Posts : 231
Points : 282
Join date : 2011-11-07

View user profile http://testlg.forumotion.co.uk

Back to top Go down

Re: handy functions

Post by Sponsored content


Sponsored content


Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum