Czy istnieje funkcja "exists" dla jQuery?

Jak sprawdzić istnienie elementu w jQuery?

Obecny kod, który mam to:

if ($(selector).length > 0) {
    // Do something
}

Czy Jest jakiś bardziej elegancki sposób, aby to zrobić? Może wtyczka lub funkcja?

Author: René, 2008-08-27

30 answers

W JavaScript wszystko jest "prawdziwe" lub "fałszywe", a dla liczb 0 (i NaN) oznacza false, Wszystko inne true. Więc możesz napisać:

if ($(selector).length)
Nie potrzebujesz tej części.
 2133
Author: Tim Büthe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-17 14:52:46

Tak!

jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}

To jest w odpowiedzi na: Herding Code podcast z Jeffem Atwoodem

 1268
Author: Jake McGraw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-13 22:37:16

Jeśli użyłeś

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
Sugerowałbyś, że łańcuchowanie było możliwe, gdy tak nie jest. Tak byłoby lepiej:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

Alternatywnie, z FAQ:

if ( $('#myDiv').length ) { /* Do something */ }

Można również użyć następujących. Jeżeli w tablicy obiektu jQuery nie ma wartości, to otrzymanie pierwszej pozycji w tablicy zwróci undefined.

if ( $('#myDiv')[0] ) { /* Do something */ }
 331
Author: Jon Erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-30 08:09:35

Możesz użyć tego:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }
 104
Author: Yanni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-29 04:43:15

Najszybszym i najbardziej semantycznym sposobem na sprawdzenie istnienia jest użycie zwykłego JavaScript:

if (document.getElementById('element_id')) {
    // Do something
}

Jest nieco dłuższa do zapisania niż alternatywa długości jQuery, ale wykonuje się ją szybciej, ponieważ jest natywną metodą JS.

I jest to lepsze niż alternatywa pisania własnej funkcji jQuery. Ta alternatywa jest wolniejsza, z powodów podanych przez @ snover. Ale to również sprawiłoby innym programistom wrażenie, że funkcja exists() jest czymś nieodłącznym elementem jQuery. JavaScript byłby / powinien być rozumiany przez innych edytujących Twój kod, bez zwiększonej wiedzy.

NB: zwróć uwagę na brak ' # ' przed element_id (ponieważ jest to zwykły JS, nie jQuery).

 77
Author: Magne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-11 12:37:09

Możesz zapisać kilka bajtów pisząc:

if ($(selector)[0]) { ... }

To działa, ponieważ każdy obiekt jQuery również maskuje się jako tablica, więc możemy użyć operatora array dereferencing, aby uzyskać pierwszy element z tablicy . Zwraca undefined, jeśli w podanym indeksie nie ma elementu.

 55
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-18 09:04:47

Możesz użyć:

if ($(selector).is('*')) {
  // Do something
}
Może bardziej eleganckie.
 51
Author: Devon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-17 17:53:34

Ta wtyczka może być używana w if instrukcji jak if ($(ele).exist()) { /* DO WORK */ } lub za pomocą wywołania zwrotnego.

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

Można określić jedno lub dwa wywołania zwrotne. Pierwszy wystrzeli jeśli element istnieje, drugi wystrzeli jeśli element nie istnieje nie istnieje. Jeśli jednak zdecydujesz się przekazać tylko jedną funkcję, zostanie ona uruchomiona tylko wtedy, gdy element istnieje. Tak więc łańcuch umrze, jeśli wybrany element nie istnieje . Oczywiście, jeśli tak istnieje, pierwsza funkcja odpali i łańcuch będzie kontynuowany.

Należy pamiętać, że użycie wariantu wywołania zwrotnego pomaga utrzymać łańcuchowość - element jest zwracany i można kontynuować łączenie poleceń, jak w przypadku każdej innej metody jQuery!

Przykładowe Zastosowania

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    */
    }
})
 51
Author: SpYk3HH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-12 09:10:58

Nie ma potrzeby jQuery naprawdę. Z prostym JavaScript łatwiej i semantycznie poprawne jest sprawdzenie:

if(document.getElementById("myElement")) {
    //Do something...
}

Jeśli z jakiegoś powodu nie chcesz dodawać id do elementu, nadal możesz użyć dowolnej innej metody JavaScript zaprojektowanej do uzyskania dostępu do DOM.

JQuery jest naprawdę fajny, ale nie pozwól, aby czysty JavaScript wpadł w zapomnienie...

 45
Author: amypellegrini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-10 07:48:47

Widzę, że większość odpowiedzi tutaj są nie dokładne Jak powinny być, sprawdzają Długość elementu, może być OK w wielu przypadkach, ale nie 100%, wyobraź sobie, jeśli liczba przechodzi do funkcji zamiast, więc prototyp funkcji, która sprawdza wszystkie warunki i zwraca odpowiedź tak, jak powinna być:

$.fn.exists = $.fn.exists || function() { 
  return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
}

To sprawdzi zarówno długość jak i typ, teraz możesz to sprawdzić w ten sposób:

$(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
 45
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-28 15:02:55

Możesz użyć tego:

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something*/}
 40
Author: Amitābha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-15 07:46:58

Powodem, dla którego wszystkie poprzednie odpowiedzi wymagają parametru .length jest to, że najczęściej używają selektora jquery $(), który ma queryselectoral za zasłoną (lub używają go bezpośrednio). Metoda ta jest raczej powolna, ponieważ musi parsować całe drzewo DOM szukając wszystkich dopasowanych do tego selektora i wypełniając je tablicą.

Parametr ['length'] nie jest potrzebny ani użyteczny, a kod będzie o wiele szybszy, jeśli użyjesz bezpośrednio document.querySelector(selector), ponieważ zwraca pierwszy element, który pasuje lub null, jeśli nie został znaleziony.

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;

Jednak ta metoda pozostawia nam zwracany rzeczywisty obiekt; co jest w porządku, jeśli nie będzie zapisywany jako zmienna i używany wielokrotnie(w ten sposób zachowując odniesienie wokół jeśli zapomnimy).

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 */

W niektórych przypadkach może to być pożądane. Można go użyć w pętli for w następujący sposób:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;

Jeśli rzeczywiście nie potrzebujesz elementu i chcesz uzyskać / zapisać tylko true / false, po prostu podwoić nie to !! To działa na buty, które są rozwiązane, więc dlaczego knot tutaj?

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);
 36
Author: technosaurus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-13 05:24:31

Uznałem if ($(selector).length) {} za niewystarczające. Po cichu złamie Twoją aplikację, gdy selector jest pustym obiektem {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [▼ Object              ] 1
//    ► __proto__: Object

Moją jedyną sugestią jest wykonanie dodatkowej kontroli {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

Wciąż szukam lepszego rozwiązania, ponieważ to jest trochę ciężkie.

Edit: Uwaga! to nie działa w IE, gdy selector jest ciągiem znaków.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
 31
Author: Oleg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-07 17:43:29

Jest $.contains () what you want?

JQuery.contains (container, contains)

$.metoda contains() zwraca true, jeśli element DOM dostarczony przez drugi argument jest potomkiem elementu DOM dostarczonego przez pierwszy argument, niezależnie od tego, czy jest bezpośrednim potomkiem, czy zagnieżdżonym głębiej. W przeciwnym razie zwraca false. Obsługiwane są tylko węzły elementu; jeśli drugi argument jest węzłem tekstu lub komentarza, $.contains() zwróci false.

Uwaga: pierwszym argumentem musi być element DOM, a nie obiekt jQuery lub zwykły obiekt JavaScript.

 28
Author: hiway,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-17 08:48:57

Możesz sprawdzić, czy element jest obecny lub nie używając długości w java script. Jeżeli długość jest większa niż zero to element jest obecny jeśli długość jest równa zero to element nie występuje

// 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
}
 28
Author: Anurag Deokar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-11 13:21:18
$(selector).length && //Do something
 24
Author: SJG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-28 12:58:08

Jest to bardzo podobne do wszystkich odpowiedzi, ale dlaczego nie użyć operatora ! dwa razy, aby uzyskać wartość logiczną:

jQuery.fn.exists = function(){return !!this.length};

if ($(selector).exists()) {
    // the element exists, now what?...
}
 23
Author: Santiago Hernández,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 03:31:21

Sprawdzanie istnienia elementu jest dokładnie udokumentowane na oficjalnej stronie jQuery!

Użyj .length własność kolekcji jQuery zwracanej przez Twoją selektor:

if ($("#myDiv").length) {
    $("#myDiv").show();
}

Zauważ, że nie zawsze jest konieczne sprawdzanie, czy element istnieje. Poniższy kod pokaże element, jeśli istnieje, i nic nie zrobi (bez błędów) jeśli nie:

$("#myDiv").show();
 23
Author: Tilak Maddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-10 10:31:46

Spróbuj przetestować DOM element

if (!!$(selector)[0]) // do stuff
 21
Author: guest271314,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-09 02:55:59

Zainspirowany odpowiedź hyway wymyśliłem co następuje:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}

JQuery.contains pobiera dwa elementy DOM i sprawdza, czy pierwszy zawiera drugi.

Użycie document.documentElement jako pierwszego argumentu spełnia semantykę metody exists, gdy chcemy zastosować ją wyłącznie do sprawdzenia istnienia elementu w bieżącym dokumencie.

Poniżej zestawiłem fragment, który porównuje jQuery.exists() z podejściami $(sel)[0] i $(sel).length które zwracają truthy wartości dla $(4) podczas gdy $(4).exists() zwraca false. W kontekście sprawdzania istnienia elementu w DOM wydaje się, że jest to pożądany wynik.

$.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>
 20
Author: Oliver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:32

Po prostu lubię używać zwykłego waniliowego javascript do tego.

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}
 18
Author: Sanu Uthaiah Bollera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-18 22:37:03

Miałem przypadek, w którym chciałem sprawdzić, czy obiekt istnieje wewnątrz innego, więc dodałem coś do pierwszej odpowiedzi, aby sprawdzić selektor wewnątrz selektora..

// 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;
};
 16
Author: jcreamer898,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-05 21:02:46

Natknąłem się na to pytanie i chciałbym podzielić się fragmentem kodu, którego obecnie używam:

$.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;
}

A teraz mogę napisać taki kod -

$("#elem").exists(function(){
    alert ("it exists");
}).otherwise(function(){
    alert ("it doesn't exist");
});

Może wydawać się dużo kodu, ale gdy jest napisany w CoffeeScript jest dość mały:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       otherwise: (fallback) ->            
            fallback.call() if not exists
 16
Author: Eternal1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-16 09:17:47

A może:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

Jest to bardzo minimalne i oszczędza konieczności załączania selektora z $() za każdym razem.

 15
Author: GSTAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-04 21:15:45

No need for jQuery

if(document.querySelector('.a-class')) {
  // do something
}
 15
Author: Pawel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-28 10:43:34

Używam tego:

    $.fn.ifExists = function(fn) {
      if (this.length) {
        $(fn(this));
      }
    };
    $("#element").ifExists( 
      function($this){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
      }
    ); 

Wykonaj łańcuch tylko wtedy, gdy istnieje element jQuery- http://jsfiddle.net/andres_314/vbNM3/2/

 11
Author: andy_314,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-01 21:56:05

Oto moja ulubiona metoda exist w jQuery

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

I inne wersje obsługujące callback, gdy selektor nie istnieje

$.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);
            }
        }
    });
};

Przykład:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);
 9
Author: ducdhm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-08 17:06:55

$("selector") podaj obiekt, który posiada length Dane. Jeśli elementy są zdefiniowane w selektorze, zostaną pobrane z obiektu. Więc jeśli sprawdzisz jego długość, już możesz znaleźć, czy istnieje jakiś element. W javascript 0 == false również null == false . Jeśli nie otrzymasz 0 twoje kody będą działać.

if($("selector").length){
   //code in the case
} 
 9
Author: Kamuran Sönecek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-16 09:07:59
if ( $('#myDiv').size() > 0 ) { //do something }

size() zlicza liczbę elementów zwróconych przez selektor

 8
Author: sth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-08 06:42:16

Nie musisz sprawdzać czy jest większa niż 0 Jak $(selector).length > 0, $(selector).length to wystarczy i elegancki sposób, aby sprawdzić istnienie elementów. Nie sądzę, że warto pisać funkcję tylko do tego, jeśli chcesz zrobić więcej dodatkowych rzeczy, tak.

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
 8
Author: Andrei Todorut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-20 09:43:38