4

Using javascript, is it possible to associate a datalist with an input without setting the id and list attributes to a string?

The HTML5 datalist element is typically (and maybe exclusively) associated with an input element by setting the input's list attribute to the id attribute of the datalist:

<input list="animals">
<datalist id="animals">
  <option value="Bear">
  <option value="Cat">
  <option value="Dog">
</datalist> 

These attributes would be unnecessary if the input element could encapsulate the datalist with a closing tag:

<input>
    <datalist>
      <option value="Bear">
      <option value="Cat">
      <option value="Dog">
    </datalist> 
</input>

However, this does not produce auto-suggestions like the previous markup does.

Let's say you want to create an ecmascript module that exports a div containing an input that has a datalist. Furthermore, let's also assume that this module will be consumed by numerous websites on the internet.

Exporting this div, already containing id and list attributes, could cause a naming conflict on that webmaster's website.

Other than using an obscure naming convention for the id, is there a way of exporting this module in a manner that makes it impossible to cause naming conflicts with all sites on the internet?

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • 1
    The spec for the input element says about the list attribute that "The value must be the id of a element in the same document." So I don't think there is another way than using id. – ecg8 May 27 '18 at 03:40
  • 1
    As @ecg8 says [the spec](https://www.w3.org/TR/html50/forms.html#the-datalist-element) doesn't list any other possibility. Best you can do is generate an ID in JS that's as unique as possible, reducing collision probability. [This question](https://stackoverflow.com/questions/3231459/create-unique-id-with-javascript) has some ways to do that. – Vasan May 27 '18 at 03:47
  • It is too bad the input cannot encapsulate the datalist. And, it is also too bad that the datalist cannot be binded directly to the input at the Javascript-DOM level without having to id anything. Thanks guys. – Lonnie Best May 27 '18 at 04:00

0 Answers0