How to add HTML datalist values from array with JavaScript?

Sometimes, we want to add HTML datalist values from array with JavaScript.

In this article, we’ll look at how to add HTML datalist values from array with JavaScript.

How to add HTML datalist values from array with JavaScript?

To add HTML datalist values from array with JavaScript, we can create option elements with document.createElement.

For instance, we write:

<input name="fruit" list="list" />
<datalist id="list"></datalist>

to add the input and datalist element for the input.

Then we write:

const fruits = ['apple', 'orange'];
const list = document.getElementById('list');

for (const f of fruits) {
  const option = document.createElement('option');
  option.value = f;
  list.appendChild(option);
};

We get the input with document.getElementById.

Then we loop through each element in fruits with a for-of loop.

In the loop, we call document.createElement to create an option element.

Then we set the option.value property’s value to f.

Next, we call list.appendChild with option to add the option element to the datalist element.

Conclusion

To add HTML datalist values from array with JavaScript, we can create option elements with document.createElement.