14

How can I determine if an element exists on a page... for instance...

$('select[name="modifier_option"]')

If that select box exists on the screen I need to validate it's value on the page to ensure it's value is > 0, but if it doesn't exist I don't need to worry about it.

Ben
  • 60,438
  • 111
  • 314
  • 488

3 Answers3

21
    if( $('select[name="modifier_option"]').length )
{
     // it exists
}
Shawn
  • 7,235
  • 6
  • 33
  • 45
4

copy/paste from here: Is there an "exists" function for jQuery?

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

if ($(selector).exists()) {
    // Do something
}
Community
  • 1
  • 1
Silver Light
  • 44,202
  • 36
  • 123
  • 164
0

I answered this same question with the following plugin here. Please visit answer for full details on creating of plugin.


The following plugin would allow you to use a callback feature (staying inline with jQuery style markup) if the element exist. So for your example, you might do something like:

$('select[name="modifier_option"]').exist(function() {
    if ($(this).val() > 0) {
        /*  DO WORK */
    }
    else {
        /*  is not greater than 0
            DO OTHER WORK   */
    }
})

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') {    //  has at least one Callback Method
                    var exist =  ele.length > 0 ? true : false; //  strict setting of boolean
                    if (exist) {    // Elements do 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 {  //  has NO callback method, thus return if exist or not based on element existant length
                    if (ele.length <= 1) return ele.length > 0 ? true : false; //   strict return of boolean
                    else return ele.length; //  return actual length for how many of this element exist
                }

                return false; //    only hits if something errored!
            }
        });
        $.fn.extend({
            exist: function() {
                var args = [$(this)];
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                return $.exist.apply($, args);
            }
        });
    }
})(jQuery);

jsFiddle

Community
  • 1
  • 1
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • can you explain what's on your version better then the "normal" `!!jQuery("selctor").length` ? (use this directly or take this as return value of .exists() ) – nbar Oct 03 '13 at 14:40
  • @nbar, you can simply use an if check if you like. My plugin suggestion, may not be "*better*" as much as "*prefered*" in that it provides readability in continued *jQuery markup*. It also provides *callback functionality*, thuus the use in my example above. The *single* callback will only fire if the element *exist*, thus replacing the `!!` or `if` check with *typical* jQuery markup. On the side, if a second callback is added in the parameters, it will fire if the element(s) do(es) not exist. – SpYk3HH Oct 03 '13 at 15:00
  • @nbar I should also mention, you can still use it as `!!jQuery("selector").exist()` and simply get a **BOOLEAN** return, *or*, if you choose to use the first callback param, then you *maintain jQuery chainability*. Thus you could continue to make calls on the *existing* elements. For example: `$('selector').exist(function(){/*dowork*/}).css('color', 'red')` And if you're wondering y i ddn't have just `.exist()` return element, its because it wouldn't make since. If you were going to use it for chainability that way, then you don't even need it. You can just simply make your calls. – SpYk3HH Oct 03 '13 at 15:03
  • Hmm I don't see any real case for that. `if(!!jQuery("selector").length) { do1() } else do2() }` vs `$('selector').exist(do1(), do2()}`. I have to say I like the first more, u directly see what happens. Also `$('selector').exist().css("do", "something")` does the same then `$('selector').css("do", "something")`. While your function can give the length (an int) as returnvalue and int don't have the function `.css()` – nbar Oct 03 '13 at 15:12
  • `if(jQuery("selector").exist()) { do1() } else do2() }` will be fine if you work with people who are not familiar with JS. Thats the only case I see. Maybe you can show me more? – nbar Oct 03 '13 at 15:13
  • @nbar "`While your function can give the length (an int) as return value and int don't have the function .css()`" You aren't reading everything through are you? I've already given you the answer to that. If you want to know more click the link to my original answer posting and see more info on it. – SpYk3HH Oct 03 '13 at 15:17