使用jQuery检查ID是否存在

sta*_*inu 11 javascript jquery

可能重复:
查找元素是否存在于整个html页面中

有没有办法检查jQuery中是否存在ID $('#ID')

例如:

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

运行append()后,我想检查我的ID $('#456')是否存在.如果它退出我想要更改文本,否则我想添加一个新的

  • .

    $(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>');
                        });
                    }
                });
            });
        });
    
    Run Code Online (Sandbox Code Playgroud)
  • Pau*_*ing 25

    if ($('#456').length)
    {
     /* it exists */
    }
    else
    {
     /* it doesn't exist */
    }
    
    Run Code Online (Sandbox Code Playgroud)