JQuery: you cannot use the find method twice on the same object

I am currently trying to use the "jquery" search method for an object twice, but this does not allow me to do this, only the first instance of "find" works. Here is the code 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 fine, except for the last method "find", it does not delete elements with the class ".delete_phone".

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

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

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

Does anyone know what is happening or is there a way to solve this problem?

Thanks!

+4
source share
2 answers

You will need .end() to return to the chain (so you do not look inside the previous .find() ):

 $("#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 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 
+10
source

It sounds like you're trying to squeeze a lot of queries into one line when you really don't need it. I'm not quite sure what you are trying to do, but I would deal with this more.

Instead, divide it into three simple queries:

 var numbers = $("#phone_numbers > p:first-child");//grab the data you want numbers.insertBefore("#phone_numbers > span:last-child");//insert it where you want $("#phone_numbers .delete_phone').remove();//remove numbers with class 'delete_phone' 

Not sure what you are trying to do for the val () part, since you are not storing the value in a variable and you are not changing the value.

If you need additional help message.

Sh.

+1
source

All Articles