Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
If for any reason you don't want to put an id to the element, you can still use all the other javascript methods designed to access the DOM, such as getElementsByTagName, DOM index, child selector, etc.
jquery es really cool, but don't let pure js to fall into oblivion...
The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:
if (document.getElementById('element_id')) { // Do something }
It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.
And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.
NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).
I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..
Yes!
ReplyDeletejQuery.fn.exists = function(){return this.length>0;}
if ($(selector).exists()) {
// Do something
}
There you go!
This is in response to: Herding Code podcast with Jeff Atwood
In JavaScript, everything is truthy or falsy and for numbers, 0 means false, everything else true. So you could write:
ReplyDeleteif ($(selector).length)
and you don't need that "> 0" part.
if you used:
ReplyDeletejQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
you would imply that chaining was possible when it is not.
This would be better
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
EDIT
Just found this in the FAQ:
http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_exists.3F
if ( $('#myDiv').length ) { //do something }
EDIT 2
you could also use the following. If there are no values in the jQuery obj array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { //do something }
you can use this
ReplyDelete// if element exists
if($('selector').length){ //do something }
// if element not exists
if(!$('selector').length){ //do something }
You can use:
ReplyDeleteif ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.
ReplyDeletevar $target = $({});
console.log($target, $target.length);
// Console output:
// -------------------------------------
// [▼ Object ] 1
// ► __proto__: Object
My only suggestion is to perform an additional check for {}.
if ($.isEmptyObject(selector) || !$(selector).length) {
throw new Error('Unable to work with the given selector.');
}
I'm still looking for a better solution though as this one is a bit heavy.
Edit: WARNING! This doesn't work in IE when selector is a string.
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
if ( $('#myDiv').size() > 0 ) { //do something }
ReplyDeletesize() counts the number of elements returned by the selector
I have found that sometimes .length throws an error, but [element locator].size() > 0 works reliably
ReplyDeleteThere's no need for jquery really. With plain JavaScript its easier and semantically correct to check for:
ReplyDeleteif(document.getElementById = "myElement") {
//do something...
}
If for any reason you don't want to put an id to the element, you can still use all the other javascript methods designed to access the DOM, such as getElementsByTagName, DOM index, child selector, etc.
jquery es really cool, but don't let pure js to fall into oblivion...
The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:
ReplyDeleteif (document.getElementById('element_id')) {
// Do something
}
It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.
And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.
NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).
I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..
ReplyDelete// Checks if an object exists.
// Usage:
//
// $(selector).exists()
//
// Or:
//
// $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
return selector ? this.find(selector).length : this.length;
};
you can use jQuery's own "isEmptyObject" : http://api.jquery.com/jQuery.isEmptyObject/
ReplyDeleteif(!$.isEmptyObject('selector')) { // Do something }
Learning by doing... your best option would be what Tim Büthe suggests:
if ($(selector).length)
You can also run a function only if it exists.
ReplyDelete$.fn.ifExists = function(error, fn) {
if (this.length) {
$(fn(this));
}
else {
alert(error);
}
};
Implementation: Hide if it exists
$("a.next").ifExists( function(t) { t.hide(); } );
But you don't actually need to do this for hiding because it will return the jquery object either way.
$.fn.ifExists = function(error, fn) {
if (this.length) {
$(fn(this));
}
else {
alert(error);
}
};
$('#button').ifExists("#button does not exits", function(){
alert("Work");
});
great code, added error statement for my own use.
if ($('selector')!=null)
ReplyDelete{
// Do something
}
or shorter...
if (!!$('selector'))
{
// Do something
}