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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With