I’m a bit confused the last couple a days. I use my JQUERY selectors whenever I like… but I didn’t check whether a selector exist or not, instead I used the .each function.
var exist = function(obj){
var returnObject ={};
for(var key in obj){
if(obj[key].length){
returnObject[key] = obj[key];
}else {
return false;
}
}
return returnObject;
}
//define all your selectors that would be needed for core functionality.
var activeSelectors = exist({
selList : $('div.selectorone'),
selTag : $('a#tagtwo'),
selFloat : $(div.float) /*etc etc*/
})
if (activeSelectors) {
console.log('all my core selectors are here!');
/* do Stuff*/
}
I know this looks a bit much, especially if you need only one selector, but I can’t figure out a better way (except a lame if statement at every selector). I saw people using
$('div#mySelector').each(function(){ /* do stuff*/});
but I don’t agree that it’s nice. Notice that #mySelector (because it’s an id) is only once allowed.
I would love the feedback. Please consider the performance vs Nice programming.
for more info please comment below or contact me!
If I really wanted to avoid just using a plain
ifstatement, then I’d probably just go with a simple function like this:And invoke it like this:
Or:
I do think you’re over-engineering the problem though. All you really need to do is check the
lengthproperty on each of the selections you’ve made (i.e. thelist,tag,floatvariables).Also, performance is a complete non-issue here; is the method of checking whether the elements exist actually going to affect the user experience for your site? As Donald Knuth said: