I’m creating an HTMLInputElement in Typescript, which I intend to use as a "slider" by setting the input element’s type
field to "range"
.
According to MDN Web Docs, I can make this slider fancier by creating an instance of an HTMLDatalistElement, giving the datalist an id
, and referencing the datalist’s id
via the slider’s list
field. This will not only give my slider some tick marks to denote where the slider cursor is currently located, but I can then set the datalist’s HTMLOptionElement’s label
field to introduce labelled tick marks.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range#adding_labels
However, Deno/TS-Node complains with this error:
error: TS2540 [ERROR]: Cannot assign to 'list' because it is a read-only property.
inputElement.list = datalistId;
and Google Chrome complains with this error:
Uncaught TypeError: Cannot set property list of #<HTMLInputElement> which has only a getter
Since the MDN Web Docs clearly show that this fields is meant to be used, I attempted to silence the Deno/TS-Node error by ignoring it via:
// @ts-ignore
This solution did not work, and resulted in the above Google Chrome runtime error.
I don’t understand why this field is allowed to be set when constructing an HTMLInputElement via an .html
file, but you aren’t allowed to use it when creating an instance of an HTMLInputElement dynamically via Javascript/Typescript. Being able to dynamically set a slider’s tick mark labels would be very nice.
2
Answers
According to the HTML specification, the
list
content attribute is indeed specified to contain the ID of a correspondingdatalist
element:However, the
input
element’slist
IDL attribute (as specified in the DOM interface) is read-only, and returns the actualHTMLDataListElement
instead of its ID:You can, however, manipulate the
list
content attribute using thesetAttribute()
function, and set thedatalist
ID on theinput
element that way:There is a difference between an attribute in HTML
<tag attribute="value">
, and an attribute of that anElement
.The attributes retrieved from the HTML are stored in
NamedNodeMap attributes;
and can be controlled using e.g.setAttribute
andgetAttribute
.The attribute an DOM Elements (that inherit from
Element
) do not need (even if they have the same name) to have the same value, their value is derived from theAttr
stored inattributes
.If you take a look at this example, you can see that there is a difference in behavior depending on which one you manipulate and retrieve:
So for
list
the attribute of the DOM Element is created based on what is set for the AttributeNode
with the name list (which is an ID).The
list
attribute of the DOM Element is probably set to readonly which contains a list of elements, because that list could not be mapped back to an ID.