Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from datalist dynamically

I am try to remove an option from a datalist dynamically but I cannot seem to get anything to work.

I have tried using .remove but instead of removing a specific option it removes the entire datalist.

Here is the code,

var cList = document.querySelector("#Options");
    cList.remove(0);

This is the datalist,

<datalist id="Options">
        <option id="O1" value="tut">Test</option>
        <option id="O2" value="tut2">Test2</option>
</datalist>

This is the result of the code running,

<form id="form1"> </form>

If you remove the cList.remove(0), you get this,

<form id="form1">
<datalist id="Options">
    <option id="O1" value="tut">Test</option>
    <option id="O2" value="tut2">Test2</option>
</datalist>
</form>

Thanks guys.

like image 977
DEFAULT Avatar asked May 19 '26 04:05

DEFAULT


2 Answers

You're using remove incorrectly. Simply remove the right option, like:

cList.children[0].remove()

Note:

  • The remove method is used to remove the current element it's being run on, hence your element gets deleted.
  • What we've done above is to run remove() on the second child by accessing cList's child nodes and deleting the one at index 0.
like image 116
AP. Avatar answered May 21 '26 17:05

AP.


You can remove an option directly if you have the id for it. However, you cannot have a purely numeric id. Rename your option id to something like "option1" and you can use the following.

var cList = document.querySelector("#option1");
cList.remove(0);
like image 44
Grax32 Avatar answered May 21 '26 17:05

Grax32