if ($.exist('#eleID')) { /* DO WORK */ } // param as STRINGif ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECTif ($('#eleID').exist()) { /* DO WORK */ } // enduced on jQuery OBJECT
$.exist('#eleID', function() { // param is STRING && CALLBACK METHOD/* DO WORK *//* This will ONLY fire if the element EXIST */}, function() { // param is STRING && CALLBACK METHOD/* DO WORK *//* This will ONLY fire if the element DOES NOT EXIST */})
$('#eleID').exist(function() { // enduced on jQuery OBJECT with CALLBACK METHOD/* DO WORK *//* This will ONLY fire if the element EXIST */})
$.exist({ // param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHODelement: '#eleID',callback: function() {/* DO WORK *//* This will ONLY fire if the element EXIST */}})
function elementIfExists(selector){ //named this way on purpose, see belowreturn document.querySelector(selector);}/* usage: */var myelement = elementIfExists("#myid") || myfallbackelement;
var myel=elementIfExists("#myid");// now we are using a reference to the element which will linger after removalmyel.getParentNode.removeChild(myel);console.log(elementIfExists("#myid")); /* null */console.log(myel); /* giant table lingering around detached from document */myel=null; /* now it can be garbage collected */
在某些情况下,这可能是需要的。它可以像这样在for循环中使用:
/* locally scoped myel gets garbage collected even with the break; */for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))if (myel == myblacklistedel) break;
// These by Idif ($("#elementid").length > 0) {// Element is Present} else {// Element is not Present}
// These by Classif ($(".elementClass").length > 0) {// Element is Present} else {// Element is not Present}
这里是不同情况的完整示例,以及使用Direct if on jQuery选择器检查元素是否存在的方法,因为它返回数组或元素,所以可能会或可能不会工作。
var a = null;
var b = []
var c = undefined ;
if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}// output: a doesn't exit
if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}// output: b exist
if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}// output: c doesn't exit
$(document).ready(function() {$("#btnCheck").click(function() {//address is the id so IsId is true. if address is class then need to set IsId falseif (exist("address", true)) {alert("exist");} else {alert("not exist");}});});
//you can check if it isnt defined or if its falsy by using ORconsole.log( $(selector) || 'this value doesnt exist' )
//or run the selector if its true, and ONLY trueconsole.log( $(selector) && 'this selector is defined, now lemme do somethin!' )
//sometimes I do the following, and see how similar it is to SWITCHconsole.log(({ //return something only if its in the method name'string':'THIS is a string','function':'THIS is a function','number':'THIS is a number','boolean':'THIS is a boolean'})[typeof $(selector)]||//skips to this value if object above is undefined'typeof THIS is not defined in your search')