SO Help: If element exists, do X (jQuery)

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

(function($) {
	if (!$.exist) {
		$.extend({
			exist: function(elm) {
				if (typeof elm == null || elm == undefined) return false;
				
				if (typeof elm == "object" && elm instanceof jQuery && elm.length) {
					if ($.contains(document.documentElement, elm[0])) return true;
				}
				else if (typeof elm == "string") {
					if ($(elm).length) return true; 
				}
				
				return false;
			}
		});
		$.fn.extend({ exist: function() { return $.exist($(this)); } });
	}
})(jQuery);

$("tbody").append(
    $("<tr />").append( $("<td />").append($("<p />").text("#eleID")), $("<td />").append($("<p />").text($("#eleID").exist())) ),
    $("<tr />").append( $("<td />").append($("<p />").text(".class-name")), $("<td />").append($("<p />").text($(".class-name").exist())) ),
    $("<tr />").append( $("<td />").append($("<p />").text("div:last")), $("<td />").append($("<p />").text($("div:last").exist())) ),
    $("<tr />").append( $("<td />").append($("<p />").text("#noBob")), $("<td />").append($("<p />").text($("#noBob").exist())) )
);