clear html select option group
I know you can clear options by doing the follow开发者_JAVA技巧ing:
dropDownList.options.length = 0;
Is there a way to clear option groups? Seems like the only way is to remove nodes one at a time.
Try getting ahold of the optgroup
element and then remove it from the DOM:
<body>
<select id="mySelect" onchange="npup(this);">
<optgroup label="Foo" id="foo_group">
<option value="foo0">foo0</option>
<option value="foo1">foo1</option>
</optgroup>
<optgroup label="Bar" id="bar_group">
<option value="bar0">bar0</option>
<option value="bar1">bar1</option>
</optgroup>
<option value="kill_foo">Remove foo</option>
</select>
<script type="text/javascript">
function npup(selectElem) {
// get value and check it
var value = selectElem.value, foo;
if (value==='kill_foo') {
// retrieve optgroup
foo = document.getElementById('foo_group');
// remove the group from its parent
foo.parentNode.removeChild(foo);
}
}
</script>
</body>
How about:
document.getElementById("foo_group").innerHTML = '';
精彩评论