1

I'm writing a lightning web component in which I have to assign a <datalist> element to one of my <input> elements' list property, in order to bind them.

For some reason, this JS line:

const streetsListId = this.template.querySelector('streetdatalist').id;

Throws this JS error message:

Cannot read property 'id' of null

Web component HTML:

<template>
    <div class="container">
        <input  id="inputstreet"
                name="inputstreet"
                type="text"
                list="streetdatalist"
                label="Search"
                onkeydown={onStreetChange}
                onblur={onStreetChange} />

        <datalist id="streetdatalist">
             <template for:each={streets} for:item='street'>
                 <option key={city.cityCode}>{city.cityName}</option>
             </template>
        </datalist>
    </div>
</template>

Web component JS:

renderedCallback() {
    if (this.initialized) {
        return;
    }
    this.initialized = true;

    const streetsListId = this.template.querySelector('streetdatalist').id;
    this.template.querySelector('inputstreet').setAttribute('list', streetsListId);
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103

1 Answers1

2

Solved it by changing the querySelector with '[data-id=:

const citiesListId = this.template.querySelector('[data-id="streetdatalist"]').id;
Koby Douek
  • 16,156
  • 19
  • 74
  • 103