Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Can't use the "find" method twice on a single object

I'm currently trying to use the jquery "find" method on an object twice but it isn't letting me do it, only the first instance of "find" is working. Here is the code that I would like to run...

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').find('.delete_phone').remove();

The above code works just fine except for the last "find" method, it isn't removing the elements with a ".delete_phone" class.

However, if I change the code to look like this...

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.delete_phone').remove();

It does remove the elements with a ".delete_phone" class. I assume this is because I can't use the "find" method twice in a row, but I'm not sure.

Does anyone know what's going on or if there is a way around this problem?

Thanks!

like image 920
lewisqic Avatar asked Dec 21 '22 20:12

lewisqic


1 Answers

You need a .end() to hop back in the chain (so you're not looking inside the previous .find() results), like this:

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').end().find('.delete_phone').remove();

Broken down view:

$("#phone_numbers > p:first-child").clone(true)
  .insertBefore("#phone_numbers > span:last-child")
  .find('.phone_type, .phone_number, .user_phones_id') //look in the cloned <p>
  .val('')                                             //empty those inputs
  .end()                                               //hope back to the <p>
  .find('.delete_phone')                               //look in the clone <p>
  .remove();                                           //remove those elements
like image 195
Nick Craver Avatar answered Dec 24 '22 11:12

Nick Craver