Monday, October 15, 2007

10 great javascript functions

I haven't found time to go back and discuss these functions, but here they are.

//this function is case insensitive
String.prototype.beginsWith = function(t) {
return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}



function isInt (str)
{
var i = parseInt (str);
if (isNaN (i))
return false;
if (i.toString() != str)
return false;
return true;
}



function alert_obj(obj)
{
var str2='';
for(s in obj)
str2+= "obj["+s+"]"+obj[s]+"\n";
alert(str2);
}



function xml_text_node(elem,nam)
{
try{
return elem.getElementsByTagName(nam)[0].firstChild.nodeValue;
}
catch(e){
return "";
}
}


function count_children(myElement)
{
if (!myElement)
return 0;
var count=0;
var child = myElement.firstChild;
while (child!=null)
{
count++;
child = child.nextSibling;
}
return count;
}




function removeChildren(list)
{
if (list==null) return;
var child = list.firstChild;
while(child!=null)
{
list.removeChild(child);
child = list.firstChild;
}
}


function DOMelement(txt)
{
var o = new Object();
o.elementname = txt;
o.attributes = new Object();
o.innerHTML = '';
o.innerText = '';
o.createElement = function()
{
var attribute_str = '';
for(attrib_name in o.attributes)
attribute_str+= attrib_name+"='"+escape(o.attributes[attrib_name])+"'";

var element;
try
{//IE
element = document.createElement("<"+o.elementname+" "+attribute_str);
}
catch (e)
{
element = document.createElement( o.elementname );
for(attrib_name in o.attributes)
element.setAttribute( attrib_name , o.attributes[attrib_name] );
}
if (o.innerHTML.length>0)
element.innerHTML = o.innerHTML;
else if (o.innerText.length>0)
element.appendChild( document.createTextNode(o.innerText) );
return element;
}

o.setAttribute = function(attribute,attribute_value)
{
o.attributes[attribute] = attribute_value;
}
return o;
}


usage:
var e = DOMelement('div');
e.setAttribute('asdfs','asdfs');
e.setAttribute('asdfs','asdfs');
e.setAttribute('asdfs','asdfs');
var element = e.createElement();

This is the ultimate, because it works in IE as well as compliant browsers.