I'm to create a html5 input field with an attached datalist by JavaScript. I'm not having any issues creating these dom nodes, but I am having trouble setting the list
attribute value using pure JavaScript. Is this possible? I've checked the functionality of the node and the value of list
is there, but whenever I try and set it no new value is assigned. Does anybody have any ideas?
Here's an example in code.
var _form = document.body.appendChild(document.createElement('form')),
_input = _form.appendChild(document.createElement('input')),
_datalist = _form.appendChild(document.createElement('datalist'));
_input.list = 'exampleList';
_input.datalist_id = 'exampleList';
_input.className = 'getme';
_datalist.id = 'exampleList';
for (var i = 0; i < 5; i++) {
var _option = _datalist.appendChild(document.createElement('option'));
switch(i){
case i:
_option.value = i;
break;
};
};
Edit
I have found a method of doing this via the element.setAttribute();
method. How would one go about doing this in a syntax similar to (for example) element.className = 'value';
.
Thank you in advance!
According to MDN there is no property to set that attridute directly. So it looks like you're stuck with setAttribute()
You should also note that DOM manipulations come with some performance ovehead so it is some times best to minimise them. You might want to consider the following:
var _form = document.body.appendChild(document.createElement('form')),
_input = _form.appendChild(document.createElement('input')),
_datalist = _form.appendChild(document.createElement('datalist'));
_datalist.id = 'exampleList';
_input.setAttribute('list','exampleList');
var _option = "";
for (var i = 0; i < 5; i++) {
_option += "<option value='" + i + "' />";
};
_datalist.innerHTML = _option;
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With