I have an issue with removing a cloned option
that I created. I can remove the original option, but nothing is removed from the clone.
var oriFruit = $('option', '#fruit').clone(); $("#fruit").find("[value='fruit1']").remove(); // works console.log(oriFruit.length); // = 4 oriFruit.find("option[value='fruit1']").remove(); // does not work console.log(oriFruit.length); // = 4, I expect 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="fruit" multiple="multiple" class="form-control"> <option value="fruit1">fruit1</option> <option value="fruit2">fruit2</option> <option value="fruit3">fruit3</option> <option value="fruit4">fruit4</option> </select>
What is wrong with this code? I tried several methods but still failed. Thanks for helping me.
Advertisement
Answer
The issue is because you’re selecting the option
elements. As such there is no root node in the jQuery object to remove()
the option
elements from. Trying to find()
instead of filter()
that collection is another issue, but not the main problem.
To fix this, clone()
the entire select
element and then find()
and remove()
the target option
. Try this:
var oriFruit = $('#fruit').clone(); $("#fruit").find("[value='fruit1']").remove(); console.log(oriFruit.children().length); // = 4 oriFruit.find("option[value='fruit1']").remove(); console.log(oriFruit.children().length); // = 3 $('body').append(oriFruit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="fruit" multiple="multiple" class="form-control"> <option value="fruit1">fruit1</option> <option value="fruit2">fruit2</option> <option value="fruit3">fruit3</option> <option value="fruit4">fruit4</option> </select> Clone: