Reputation: 1188
I'm using jQuery to append new <option>
tags to a <select>
field, and in some cases I need to remove those options without knowing the values of them.
Is it possible to remove all the options that were created by jQuery whilst leaving the original options intact?
The only way I can think of doing it is by checking they're not the values I want to keep. Hopefully is there an easier, quicker, way?
Upvotes: 2
Views: 133
Reputation: 6738
It's dirty, but here goes;
$(function() {
var myselects = $('#myselectelement');
var myoptions = myselects.html();
// now we know the state of the select on ready
var resetopts = function(sel, opt)
{
sel.html(opt);
}
// call resetopts(myselects, myoptions) when you want to reset.
});
This way you don't add any extra markup. There is a memory cost though.
I have a way to do this with DOM elements, but the above was hard enough to type from memory on a touch screen.
Upvotes: 1
Reputation: 13476
If all of the dynamic elements have been created by you, then you can use the HTML5 data-attribute to store a small piece of metadata on the elements to make this trivial.
e.g,
element.attr("data-dynamic", "true");
You can then find all dynamic elements via:
$('*[data-dynamic="true"]')
Of course if you know what type of elements this may appear on you can make it more efficient:
$('option[data-dynamic="true"]')
This has many more uses such as storing data in non-dynamically created HTML for use by JavaScript later.
NOTE: Although it is HTML5 this works in most browsers (IE4+) as it is the same as obtaining any attribute, the difference is it is considered valid HTML with a HTML5 doctype.
Upvotes: 1
Reputation: 492
You can add a property to the tags and filter on that. For example you can make them part of a class appended
and delete them that way. See for an example this fiddle.
Upvotes: 1
Reputation: 437386
Once elements are inserted into the DOM they are all equal; there is no magic "dynamically created" flag that you can check.
Of course you can always create your own methods to do so. For example, you can add a "data-dynamic"
HTML attribute or a dynamic
CSS class to the dynamically created options and then filter based on that.
Upvotes: 6