How to check function to see if parent exists - javascript

Working on a JS function: How would I check to see if a parent element exists and if it doesn't print out 'not found'. Also how do I check for a parent element with a certain className?
var findParentByClassName = function(element, targetClass) {
if (element) {
var currentParent = element.parentElement;
while (currentParent.className !== targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
} // closes loop
return currentParent;
} // closes if statement
};
I was thinking to write this:
if(element.parentElement !== targetClass) {
console.log('Parent not found');
}

This can be an example of closest() and get() Jquery functions. Of course everything in the DOM has a parent, so we will check for something special, a form with class="myclass":
var element = $(yourElement).closest('form.myclass');
if(element.get(0)){
//you got your element
}
else{
console.log('not found');
}
The method get([index]) is needed due, the selector won't return empty.

If you want to check if immediate parent has certain class, you can do it several ways:
Pure JavaScript (best performance):
if (element.parentElement.classList.contains('nameOfClass')) {}
jQuery (best jQuery performance):
if ($(element).parent().hasClass('nameOfClass')) {}
jQuery (usable for every selector, not just class, worse performance):
if ($(element).parent('.nameOfClass').length) {}

Related

Test whether an element exists [duplicate]

How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:
if ($(selector).length)
You don't need that >0 part.
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
This is in response to: Herding Code podcast with Jeff Atwood
If you used
jQuery.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)) { }
Alternatively, from the FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { /* Do something */ }
You can use this:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
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).
You can save a few bytes by writing:
if ($(selector)[0]) { ... }
This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.
You can use:
if ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.
Plugin
;;(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') {
var exist = ele.length > 0 ? true : false;
if (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 {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
return false;
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
jsFiddle
You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.
Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!
Example Uses
if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING
if ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT
if ($('#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 = METHOD
element: '#eleID',
callback: function() {
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}
})
I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:
$.fn.exists = $.fn.exists || function() {
return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement));
}
This will check both length and type, Now you can check it this way:
$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true
There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:
if(document.getElementById("myElement")) {
//Do something...
}
If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.
jQuery is really cool, but don't let pure JavaScript fall into oblivion...
You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.
The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.
function elementIfExists(selector){ //named this way on purpose, see below
return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;
However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).
var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.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 */
In some cases this may be desired. It can be used in a for loop like this:
/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
if (myel == myblacklistedel) break;
If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?
function elementExists(selector){
return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table"); /* will be true or false */
if (hastables){
/* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
alert("bad table layouts");},3000);
Is $.contains() what you want?
jQuery.contains( container, contained )
The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
You can check element is present or not using length in java script.
If length is greater than zero then element is present if length is zero then
element is not present
// These by Id
if ($("#elementid").length > 0) {
// Element is Present
} else {
// Element is not Present
}
// These by Class
if ($(".elementClass").length > 0) {
// Element is Present
} else {
// Element is not Present
}
I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.
var $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
Checking for existence of an element is documented neatly in the official jQuery website itself!
Use the .length property of the jQuery collection returned by your
selector:
if ($("#myDiv").length) {
$("#myDiv").show();
}
Note that it isn't always necessary to test whether an element exists.
The following code will show the element if it exists, and do nothing
(with no errors) if it does not:
$("#myDiv").show();
this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
No need for jQuery (basic solution)
if(document.querySelector('.a-class')) {
// do something
}
Much more performant option below (notice the lack of a dot before a-class).
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to JSBench https://jsbench.me/65l2up3t8i
$(selector).length && //Do something
Try testing for DOM element
if (!!$(selector)[0]) // do stuff
Inspired by hiway's answer I came up with the following:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains takes two DOM elements and checks whether the first one contains the second one.
Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.
Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
var testFuncs = [
function(jq) { return !!jq[0]; },
function(jq) { return !!jq.length; },
function(jq) { return jq.exists(); },
];
var inputs = [
["$()",$()],
["$(4)",$(4)],
["$('#idoexist')",$('#idoexist')],
["$('#idontexist')",$('#idontexist')]
];
for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
input = inputs[i][1];
tr = "<tr><td>" + inputs[i][0] + "</td><td>"
+ testFuncs[0](input) + "</td><td>"
+ testFuncs[1](input) + "</td><td>"
+ testFuncs[2](input) + "</td></tr>";
$("table").append(tr);
}
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
<td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
</script>
I just like to use plain vanilla javascript to do this.
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
I stumbled upon this question and i'd like to share a snippet of code i currently use:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
And now i can write code like this -
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
It might seem a lot of code, but when written in CoffeeScript it is quite small:
$.fn.exists = (callback) ->
exists = #length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists
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..
// 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;
};
How about:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
It's very minimal and saves you having to enclose the selector with $() every time.
I'm using this:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
$("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.
if($("selector").length){
//code in the case
}
Here is my favorite exist method in jQuery
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
and other version which supports callback when selector does not exist
$.fn.exist = function(onExist, onNotExist) {
return $(this).each(function() {
var target = $(this);
if (this.length > 0) {
if (typeof onExist === 'function') {
onExist.call(target);
}
} else {
if (typeof onNotExist === 'function') {
onNotExist.call(target);
}
}
});
};
Example:
$('#foo .bar').exist(
function () {
// Stuff when '#foo .bar' exists
},
function () {
// Stuff when '#foo .bar' does not exist
}
);
You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.
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
FINAL SOLUTION
if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
Demo
console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)
console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.cls-3').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-1">
<div class="cls-1 cls-2"></div>
<div class="cls-2"></div>
</div>

Exists (-like) function for jQuery? [duplicate]

How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:
if ($(selector).length)
You don't need that >0 part.
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
This is in response to: Herding Code podcast with Jeff Atwood
If you used
jQuery.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)) { }
Alternatively, from the FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { /* Do something */ }
You can use this:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
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).
You can save a few bytes by writing:
if ($(selector)[0]) { ... }
This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.
You can use:
if ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.
Plugin
;;(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') {
var exist = ele.length > 0 ? true : false;
if (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 {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
return false;
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
jsFiddle
You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.
Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!
Example Uses
if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING
if ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT
if ($('#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 = METHOD
element: '#eleID',
callback: function() {
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}
})
I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:
$.fn.exists = $.fn.exists || function() {
return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement));
}
This will check both length and type, Now you can check it this way:
$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true
There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:
if(document.getElementById("myElement")) {
//Do something...
}
If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.
jQuery is really cool, but don't let pure JavaScript fall into oblivion...
You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.
The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.
function elementIfExists(selector){ //named this way on purpose, see below
return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;
However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).
var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.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 */
In some cases this may be desired. It can be used in a for loop like this:
/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
if (myel == myblacklistedel) break;
If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?
function elementExists(selector){
return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table"); /* will be true or false */
if (hastables){
/* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
alert("bad table layouts");},3000);
Is $.contains() what you want?
jQuery.contains( container, contained )
The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
You can check element is present or not using length in java script.
If length is greater than zero then element is present if length is zero then
element is not present
// These by Id
if ($("#elementid").length > 0) {
// Element is Present
} else {
// Element is not Present
}
// These by Class
if ($(".elementClass").length > 0) {
// Element is Present
} else {
// Element is not Present
}
I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.
var $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
Checking for existence of an element is documented neatly in the official jQuery website itself!
Use the .length property of the jQuery collection returned by your
selector:
if ($("#myDiv").length) {
$("#myDiv").show();
}
Note that it isn't always necessary to test whether an element exists.
The following code will show the element if it exists, and do nothing
(with no errors) if it does not:
$("#myDiv").show();
this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
No need for jQuery (basic solution)
if(document.querySelector('.a-class')) {
// do something
}
Much more performant option below (notice the lack of a dot before a-class).
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to JSBench https://jsbench.me/65l2up3t8i
$(selector).length && //Do something
Try testing for DOM element
if (!!$(selector)[0]) // do stuff
Inspired by hiway's answer I came up with the following:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains takes two DOM elements and checks whether the first one contains the second one.
Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.
Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
var testFuncs = [
function(jq) { return !!jq[0]; },
function(jq) { return !!jq.length; },
function(jq) { return jq.exists(); },
];
var inputs = [
["$()",$()],
["$(4)",$(4)],
["$('#idoexist')",$('#idoexist')],
["$('#idontexist')",$('#idontexist')]
];
for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
input = inputs[i][1];
tr = "<tr><td>" + inputs[i][0] + "</td><td>"
+ testFuncs[0](input) + "</td><td>"
+ testFuncs[1](input) + "</td><td>"
+ testFuncs[2](input) + "</td></tr>";
$("table").append(tr);
}
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
<td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
</script>
I just like to use plain vanilla javascript to do this.
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
I stumbled upon this question and i'd like to share a snippet of code i currently use:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
And now i can write code like this -
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
It might seem a lot of code, but when written in CoffeeScript it is quite small:
$.fn.exists = (callback) ->
exists = #length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists
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..
// 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;
};
How about:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
It's very minimal and saves you having to enclose the selector with $() every time.
I'm using this:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
$("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.
if($("selector").length){
//code in the case
}
Here is my favorite exist method in jQuery
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
and other version which supports callback when selector does not exist
$.fn.exist = function(onExist, onNotExist) {
return $(this).each(function() {
var target = $(this);
if (this.length > 0) {
if (typeof onExist === 'function') {
onExist.call(target);
}
} else {
if (typeof onNotExist === 'function') {
onNotExist.call(target);
}
}
});
};
Example:
$('#foo .bar').exist(
function () {
// Stuff when '#foo .bar' exists
},
function () {
// Stuff when '#foo .bar' does not exist
}
);
You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.
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
FINAL SOLUTION
if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
Demo
console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)
console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.cls-3').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-1">
<div class="cls-1 cls-2"></div>
<div class="cls-2"></div>
</div>

Traverse DOM to determine status of parent. Return strings on conditions

This is the code I have:
var findParentByClassName = function(element, targetClass) {
if (element) {
element.parentElement === null;
console.log("No parent found");
} if else {
element.parentElement !=== targetClass;
console.log("No parent found with that class name");
} else {
var currentParent = element.parentElement;
while (currentParent.className !== targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
}
return currentParent;
}
};
I need to be able to check for two other conditions:
Check to see if the provided "element" has a parent. If it does, send a string to the console.
If it does not find a parent with the provided "targetClass" name then have it return a different string to the console.
I'm assuming this would be done via an if - if-else - else function but for the life of me, I'm just not able to get it.
Try using this (code is explained under code snippet):
var findParentByClassName = function(elem, className)
{
if(elem == null)
{
console.log("No elem");
}
else if(elem.parentNode == null)
{
console.log("No parent");
}
else
{
console.log("Found a parent, looking for an ancestor with the given class name");
var ancestor = elem.parentNode;
while(ancestor != null)
{
if(ancestor.classList.contains(className))
{
console.log("Found ancestor with correct classname");
return parent;
}
}
}
console.log("Could not find parent with correct class name.");
return null;
};
First, you double check whether or not you were actually given an element. If not, we can do nothing.
Then, we use else if - not if else - to check if the element has a parent. If it does not, we can do nothing again.
Finally, our else branch is executed if we have an element with an ancestor. From this point, we can move up the DOM tree iteratively. If we find an element whose classList contains the className we were given, we have found a matching ancestor, and return it. Otherwise, we return null.
Note that this code finds an ancestor with a matching class name, which is not necessarily a direct parent. I'm assuming this is what you want based on your code.
Now, this becomes much easier if you're using jQuery:
var findParentByClassName = function(elem, className)
{
return $(elem).closest("." + className);
};
The downside here is that you won't be able to log messages explaining
why no ancestor with the right class name could be found if one does not exist.
Here's how if-else if-else statements work:
if(condition)
{
// code to execute if the condition is true
}
else if(condition2) // condition2 is only checked if the 1st one is false
{
// code to run if condition2 is true
}
else if(condition3) // you can have 0 or more else if conditions
{
// in practice, you can have as many as you want
// there are limits, but you'll probably never reach them
// unless you're trying to
}
else
{
// code to execute if none of the conditions were true
}
Conditions are boolean expressions. These could be boolean values,
equality checks, greater than / less than, whether or not a variable
is null / undefined, so on and so forth.
I would recommend reading through a JavaScript tutorial for more information.

How to recursively search all parentNodes

I want to know, how to find out recursively all parent nodes of an element.
Suppose i have following snippet
<font>Hello</font>
In this I would like to find out whether font tag's parent node is an anchor tag or not.
Now this can be achieved by simply checking .parentNode property. But what if there are following cases like,
<font><b>Hello<b></font>
or
<font><b><u>Hello</u><b></font>
So, basically, how to know if we have reached the top most parent node ?
You can traverse from an element up to the root looking for the desired tag:
function findUpTag(el, tag) {
while (el.parentNode) {
el = el.parentNode;
if (el.tagName === tag)
return el;
}
return null;
}
You call this method with your start element:
var el = document.getElementById("..."); // start element
var a = findUpTag(el, "A"); // search <a ...>
if (a) console.log(a.id);
The following recursive function will return an ascending ordered array, with all the parents nodes for the provided DOM element, until BODY node is reached.
function parents(element, _array) {
if(_array === undefined) _array = []; // initial call
else _array.push(element); // add current element
// do recursion until BODY is reached
if(element.tagName !== 'BODY' ) return parents(element.parentNode, _array);
else return _array;
}
Usage :
var parentsArray = parents( document.getElementById("myDiv") );
You can use jQuery closest() method to get the closest ahref:
$("#your-element").closest("a").css("color", "red");
Or you can have a look at the parentsUntil method:
$("#your-element").parentsUntil("#yourWrapper", "a").first().css("color", "red");
Try it out here: http://www.lunarailways.com/demos/parents.html
I been working on similar thing. Trying to close a div if user clicks outside the div. It needs to loop through all its parent nodes.
have a look at this:
http://jsfiddle.net/aamir/y7mEY/
Here's a shorter one:
function parentByTag(el, tag) {
if(!el || el.tagName == tag) {
return el
} else {
return parentByTag(el.parentElement, tag)
}
}
Returns undefined if not found.

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:
if ($(selector).length)
You don't need that >0 part.
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
This is in response to: Herding Code podcast with Jeff Atwood
If you used
jQuery.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)) { }
Alternatively, from the FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { /* Do something */ }
You can use this:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
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).
You can save a few bytes by writing:
if ($(selector)[0]) { ... }
This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.
You can use:
if ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.
Plugin
;;(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') {
var exist = ele.length > 0 ? true : false;
if (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 {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
return false;
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
jsFiddle
You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.
Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!
Example Uses
if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING
if ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT
if ($('#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 = METHOD
element: '#eleID',
callback: function() {
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}
})
I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:
$.fn.exists = $.fn.exists || function() {
return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement));
}
This will check both length and type, Now you can check it this way:
$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true
There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:
if(document.getElementById("myElement")) {
//Do something...
}
If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.
jQuery is really cool, but don't let pure JavaScript fall into oblivion...
You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.
The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.
function elementIfExists(selector){ //named this way on purpose, see below
return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;
However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).
var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.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 */
In some cases this may be desired. It can be used in a for loop like this:
/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
if (myel == myblacklistedel) break;
If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?
function elementExists(selector){
return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table"); /* will be true or false */
if (hastables){
/* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
alert("bad table layouts");},3000);
Is $.contains() what you want?
jQuery.contains( container, contained )
The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
You can check element is present or not using length in java script.
If length is greater than zero then element is present if length is zero then
element is not present
// These by Id
if ($("#elementid").length > 0) {
// Element is Present
} else {
// Element is not Present
}
// These by Class
if ($(".elementClass").length > 0) {
// Element is Present
} else {
// Element is not Present
}
I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.
var $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
Checking for existence of an element is documented neatly in the official jQuery website itself!
Use the .length property of the jQuery collection returned by your
selector:
if ($("#myDiv").length) {
$("#myDiv").show();
}
Note that it isn't always necessary to test whether an element exists.
The following code will show the element if it exists, and do nothing
(with no errors) if it does not:
$("#myDiv").show();
this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
No need for jQuery (basic solution)
if(document.querySelector('.a-class')) {
// do something
}
Much more performant option below (notice the lack of a dot before a-class).
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to JSBench https://jsbench.me/65l2up3t8i
$(selector).length && //Do something
Try testing for DOM element
if (!!$(selector)[0]) // do stuff
Inspired by hiway's answer I came up with the following:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains takes two DOM elements and checks whether the first one contains the second one.
Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.
Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
var testFuncs = [
function(jq) { return !!jq[0]; },
function(jq) { return !!jq.length; },
function(jq) { return jq.exists(); },
];
var inputs = [
["$()",$()],
["$(4)",$(4)],
["$('#idoexist')",$('#idoexist')],
["$('#idontexist')",$('#idontexist')]
];
for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
input = inputs[i][1];
tr = "<tr><td>" + inputs[i][0] + "</td><td>"
+ testFuncs[0](input) + "</td><td>"
+ testFuncs[1](input) + "</td><td>"
+ testFuncs[2](input) + "</td></tr>";
$("table").append(tr);
}
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
<td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
</script>
I just like to use plain vanilla javascript to do this.
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
I stumbled upon this question and i'd like to share a snippet of code i currently use:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
And now i can write code like this -
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
It might seem a lot of code, but when written in CoffeeScript it is quite small:
$.fn.exists = (callback) ->
exists = #length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists
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..
// 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;
};
How about:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
It's very minimal and saves you having to enclose the selector with $() every time.
I'm using this:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
$("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.
if($("selector").length){
//code in the case
}
Here is my favorite exist method in jQuery
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
and other version which supports callback when selector does not exist
$.fn.exist = function(onExist, onNotExist) {
return $(this).each(function() {
var target = $(this);
if (this.length > 0) {
if (typeof onExist === 'function') {
onExist.call(target);
}
} else {
if (typeof onNotExist === 'function') {
onNotExist.call(target);
}
}
});
};
Example:
$('#foo .bar').exist(
function () {
// Stuff when '#foo .bar' exists
},
function () {
// Stuff when '#foo .bar' does not exist
}
);
You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.
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
FINAL SOLUTION
if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
Demo
console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)
console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.cls-3').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-1">
<div class="cls-1 cls-2"></div>
<div class="cls-2"></div>
</div>

Categories

Resources