0

I have the following jsFiddle which best demonstrates what I want to do. It is fairly self-explanatory: if an element with the same name attribute exists, do nothing; if no such element exists, append that element.

if (an element exists in the div 'selects' with name="folder3") {
    return false;
} else {
    $('#selects').append('<select name="folder3"></select>');
}

Kept it short and sweet for this one! Any help would be much appreciated.

James M
  • 18,506
  • 3
  • 48
  • 56
jacktheripper
  • 13,953
  • 12
  • 57
  • 93
  • 1
    possible duplicate of [jQuery determining if element exists on page](http://stackoverflow.com/questions/4257906/jquery-determining-if-element-exists-on-page) – Felix Kling May 11 '12 at 10:53
  • Also related [jquery select element by name attribute](http://stackoverflow.com/questions/6278423/jquery-select-element-by-name-attribute). – Felix Kling May 11 '12 at 10:56

8 Answers8

2

Something like:

if ($('#selects select[name="folder3"]').length) {

is probably what you're looking for.

http://jsfiddle.net/Ue7VQ/1/

James M
  • 18,506
  • 3
  • 48
  • 56
1
//if (an element exists in the div 'selects' with name="folder3") -yours comment
if ($('#selects').find('select[name="folder3"]').length) {
    return false;
} else {
    $('#selects').append('<select name="folder3"></select>');
}​

Live DEMO

gdoron
  • 147,333
  • 58
  • 291
  • 367
1
if ($("#selects select[name='folder3']").length>0) {
    return false;
} else {
    $('#selects').append('<select name="folder3"></select>');
}
Imdad
  • 5,942
  • 4
  • 33
  • 53
1
if ($('#selects select[name="folder3"]').length) {
    return false;
} else {
    $('#selects').append('<select name="folder3"></select>');
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1
var itemName = "folder4";
var $item = $('#selects select[name="' + itemName + '"]');

if($item.length == 0)
{
    $('#selects').append('<select name="' + itemName + '"></select>');
}

Fiddle here

Nope
  • 22,147
  • 7
  • 47
  • 72
1

Check this out. There are many other work arounds. Here I check each dropdown, not every other element in the page. http://jsfiddle.net/Ue7VQ/4/

$(function ()
  {
      $.each( $("select"), function() {
          if ($(this).attr("name") == "folder3")
          {
              alert('Do you what you want to do over here');
          }
      });
  });​
test
  • 2,538
  • 4
  • 35
  • 52
1

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:

//  first callback is "if exist",
//  second callback method is "if not exist"
$('#selects select[name="folder3"]').exist(function(exist, elements, index) { // with a param, this cb will always fire
    /*  Do work for existing elements here  */
    /*  $(this) && this work just like any other jQuery method. this is the current element worked on   */
    /*  Params:
            exist: boolean (should always be true here) if exist
            elements: complete list of elements called using your selector, in this case '#selects select[name="folder3"]'
            index: the index number within the list of elements of THIS element
    */
},
function (exist, elements) {
    /*  Do alternate work, for elements do not exist    */
    /*  Params:
            exist: boolean (should always be false here) if exist
            elements: complete list of elements called using your selector, in this case '#selects select[name="folder3"]'
    */
});

|OR|

if (!$('#selects select[name="folder3"]').exist()) {
    // element did not exist
    $('#selects').append('<select name="folder3"></select>');
}

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
0

you could try this,

function checkSelects() {
        var contains = false;
        var temp = $("#selects").children();
        $(temp).each(function () {
            if ($(this).attr("name") == "folder3")
                contains = true;
         });
        if (!contains)
            $("#selects").append('<select name="folder3"></select>');

    }
Vishal Gowda
  • 511
  • 1
  • 3
  • 11
  • If `folder3` is not the last `select` the `contains` value is re-set to `false` and a duplicate select is added. Once `contains` is set to `true` you should probably stop the iteration. I also don't think that .children() only selects the `select` elements and as such you will iterate through elements you are not interested in to begin with. – Nope May 11 '12 at 11:01
  • @FrançoisWahl thanks for the correction and as of .children() it solves jacktheripper problem. – Vishal Gowda May 11 '12 at 11:15
  • 1
    Iterating through an unknown number of elements in addition of the already unknown number of select elements sounds inefficient. But yes, it will work off course :) – Nope May 11 '12 at 11:19