[jQuery] jQuery.clean
[jQuery] jQuery.clean
Just want to help.
I think jQuery.clean function can cause trouble in some cases
And I suggest an improvement.
Current code:
clean: function(a) {
var r = [];
for ( var i = 0; i < a.length; i++ ) {
// Error will occure if a[i] == null or undefined
// 'a[i].constructor' is null or not an object
if ( a[i].constructor == String ) {
if ( !a[i].indexOf("<tr") ) {
var tr = true;
a[i] = "<table>" + a[i] + "</table>";
} else if ( !a[i].indexOf("<td") || !a[i].indexOf("<th") ) {
var td = true;
a[i] = "<table><tbody><tr>" + a[i] + "</tr></tbody></table>";
}
var div = document.createElement("div");
div.innerHTML = a[i];
if ( tr || td ) {
div = div.firstChild.firstChild;
if ( td ) div = div.firstChild;
}
for ( var j = 0; j < div.childNodes.length; j++ )
r.push( div.childNodes[j] );
} else if ( a[i].jquery || a[i].length && !a[i].nodeType )
for ( var k = 0; k < a[i].length; k++ )
r.push( a[i][k] );
// If there was a null you already have an error
// in a[i].constructor == String
// and undefined can pass thru a[i] !== null
else if ( a[i] !== null )
r.push( a[i].nodeType ? a[i] : document.createTextNode(a[i].toString()) );
}
return r;
},
Impruved code:
clean: function(a) {
var r = [];
for ( var i = 0; i < a.length; i++ ) {
// check for null or undefined
if (a[i] == null) continue;
// Filter dom elements
if (a[i].nodeType) r.push(a[i]);
// I supose every object who pass this line will have .length
// or else I think nobody misses him :)
else if(typeof a[i] == "object")
for ( var k = 0; k < a[i].length; k++ )
r.push( a[i][k] );
else {
// Just for insurance if a[i] is Number or Boolean or even Function :)
a[i] = a[i].toString();
// Old code
if ( !a[i].indexOf("<tr") ) {
var tr = true;
a[i] = "<table>" + a[i] + "</table>";
} else if ( !a[i].indexOf("<td") || !a[i].indexOf("<th") ) {
var td = true;
a[i] = "<table><tbody><tr>" + a[i] + "</tr></tbody></table>";
}
var div = document.createElement("div");
div.innerHTML = a[i];
if ( tr || td ) {
div = div.firstChild.firstChild;
if ( td ) div = div.firstChild;
}
for ( var j = 0; j < div.childNodes.length; j++ )
r.push( div.childNodes[j] );
}
}
return r;
},
And 67 characters less :)
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/