0

I'm trying to loop over a bunch of buttons to give each of them an event listener that will change the background color once I click any of them, but vs code's IntelliSense won't autocomplete the desired property I'm looking for such .style .

code snippit

const buttons = document.querySelectorAll('btn');

for(let button of buttons) {
    button.addEventListener('click', () => {
        button.*style.backgroundColor* = 'red';
    })
}

HTML

<body>
    <section id="container">
        <button class="btn">Click me</button>
        <button class="btn">Click me</button>
        <button class="btn">Click me</button>
        <button class="btn">Click me</button>
    </section>
    <script src="app.js"></script>
</body>

VS Code intellisense won't recommend the italicized code .style and .backgroundColor

it's happening of both block and scope level as will as global level.

1 Answers1

0

The issue is that document.querySelectorAll is specified to give you a NodeList containing Element objects, a general base class. Thus each button is, as far as the JavaScript IntelliSense can infer, merely an instance of Element. But the style property exists on HTMLElement. Therefore you need to 'tell' the IntelliSense engine that buttons is going to be a NodeList of HTMLElement instead, which you can accomplish with a JSDoc:

/** @type {NodeListOf<HTMLElement>} */
const buttons = document.querySelectorAll('btn');

for(let button of buttons) {
    button.addEventListener('click', () => {
        button.style.backgroundColor = 'red';
    })
}
xavc
  • 1,245
  • 1
  • 8
  • 14