Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an ID exists or not using jQuery [duplicate]

Possible Duplicate:
Finding whether the element exists in whole html page

Is there any way to check for if a ID $('#ID') exists in jQuery

Ex:

$('#cart').append('<li id="456">My Product</li>');

After running append() to something like this I want to check if my ID $('#456') exists or not. If it exits I want to change the text, else I want to append a new

  • .
    $(document).ready(function() {
            $('#RAM,#HDD').change(function() {
    
                var product = $(this).find("option:selected").attr("product");
    
                $.ajax({
                    url: 'ajax.php',
                    type: 'post',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(data) {
                        $('#cart').empty();
                        $.each(data, function(index, value) {
                            $('#cart').append('<li id="'+product+'">'+ value['price'] +'</li>');
                        });
                    }
                });
            });
        });
    
  • like image 717
    stackminu Avatar asked Jul 22 '12 12:07

    stackminu


    2 Answers

    if ($('#456').length)
    {
     /* it exists */
    }
    else
    {
     /* it doesn't exist */
    }
    
    like image 116
    Paul Fleming Avatar answered Sep 30 '22 18:09

    Paul Fleming


    You can do this to see if the selector does exist or not:

    jQuery.fn.exists = function(){return this.length>0;}
    
    if ($(selector).exists()) {
        // Do something
    }
    
    like image 23
    Tarik Avatar answered Sep 30 '22 18:09

    Tarik