Change the `list` attribute of an <input> in JavaScript
According to the Mozilla Developer Network docs, the list
attribute is read-only and actually returns a reference to a DOM element (like a <datalist>
):
list
[Read only]
HTMLElement object
: Returns the element pointed by thelist
attribute. The property may benull
if no HTML element found in the same tree.
Thus, you need to use setAttribute
to set the list by id
, and then use element.list.id
to retrieve the correct value for check
.
function change() {
console.log("Started")
var x = document.getElementById('A').value
document.getElementById('List').setAttribute('list', x)
var check = document.getElementById('List').list.id
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>