jQuery Plugin: $.exist() && $.fn.exist()
by SpYk3
HTML
<div id="eleID">This element has an ID of "eleID"</div>
<div class="class-name">This element has a class name of "class-name"</div>
<div>This is just a plain div element with no ID or class name. Select this specifc one with "div:last" jQuery selector</div>
<hr />
<table>
<thead> <tr> <th> <p>Element Selector</p> </th> <th> <p>Exist ?</p> </th> </tr> </thead>
<tbody></tbody>
</table>
CSS
div { border: 1px solid blue; margin: 1em; padding: .5em 1em; text-align: center; }
table { border-collapse: separate; border-spacing: 3px 0; margin: 0 auto; }
table, th, td { border: none; }
p { padding: .2em .5em; }
th { border-bottom: 1px solid; }
th, td { border-left: 1px solid; }
th:first-child, tr td:first-child { border-left: none; border-right: 1px solid; }
JavaScript
/*---PULIGIN---*/
(function($) {
if (!$.exist) {
$.extend({
exist: function() {
var ele, cbmExist, cbmNotExist;
if (arguments.length) {
for (x in arguments) {
switch (typeof arguments[x]) {
case 'function':
if (typeof cbmExist == "undefined") cbmExist = arguments[x];
else cbmNotExist = arguments[x];
break;
case 'object':
if (arguments[x] instanceof jQuery) ele = arguments[x];
else {
var obj = arguments[x];
for (y in obj) {
if (typeof obj[y] == 'function') {
if (typeof cbmExist == "undefined") cbmExist = obj[y];
else cbmNotExist = obj[y];
}
if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
if (typeof obj[y] == 'string') ele = $(obj[y]);
}
}
break;
case 'string':
ele = $(arguments[x]);
break;
}
}
}
if (typeof cbmExist == 'function') { // has at least one Callback Method
var exist = ele.length > 0 ? true : false; // strict setting of boolean
if (exist) { // Elements do exist
return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
}
else if (typeof cbmNotExist == 'function') {
cbmNotExist.apply(ele, [exist, ele]);
return ele;
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
}
else { // has NO callback method, thus return if exist or not based on element existant length
if (ele.length <= 1) return ele.length > 0 ? true : false; // strict return of boolean
else return ele.length; // return actual length for how many of this element exist
}
return false; // only hits if something errored!
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($,...