Check if id exists or not using jQuery

Possible duplicate:
Finding if an element exists throughout the html page

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

Example:

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

After running append () for something like this, I want to check if my ID $ ('# 456') exists. If it comes out, I want to change the text, otherwise I want to add a new one

.
 $(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>'); }); } }); }); }); 
+7
source share
4 answers
 if ($('#456').length) { /* it exists */ } else { /* it doesn't exist */ } 
+15
source

You can do this to see if a selector exists or not:

 jQuery.fn.exists = function(){return this.length>0;} if ($(selector).exists()) { // Do something } 
+2
source

Um, I'm not sure why you want to do this, but for this you need to change your code a bit.

 success: function(data) { var cart = $('#cart'); cart.empty(); $.each(data, function(index, value) { cart.append('<li id="'+product+'">'+ value['price'] +'</li>'); }); if(cart.find('#456').length) { cart.find('#456').text('Whatever you would like'); } } 

I pinned your basket selector to save the DOM search.

0
source
 function checkExists(sel) { var status = false; if ($(sel).length) status = true; return status; } 

Working example

0
source

All Articles