Why is IntelliSense not recognizing my query selected item as an element?

Viewed 991

Problem

I am trying to figure out why VSCode's IntelliSense won't suggest element object properties when I access an HTML element with:

document.querySelector();

Whenever I use the document.querySelector() method and then use the . operator to attempt to see the properties of my selected element, I don't get a list of CSS properties such as style

Example

I have a div element in my HTML file with the class 'list'

<div class='list'>

And in my .js file I am able to access this element by writing:

const listElement = document.querySelector('.list');

My problem is that when using the . operator on listElement, VSCode does not show basic properties such as style. I am still able to set things by manually typing something like

listElement.style.display = 'none';

but when I use the . operator VSCode does not suggest style and when I type style and use the .operator again it does not suggest display. My question is: How can I get Intellisense to display these properties?

Note: I am new to HTML, CSS, and Javascript so I don't know if I'm using all the correct terminology, but I tried!

1 Answers

VS Code's JavaScript IntelliSense does not know what your HTML looks like so it will assume that querySelector returns a very generic type of object. That's why you don't see suggestions for .style and some other common DOM properties. Those properties really may not exist on what querySelector returns!

However you can explicitly tell VS Code the type of the element that querySelector returns with a simple JSDoc type annotation:

/** @type {HTMLDivElement} */
const listElement =  document.querySelector('.list');

This should give you proper IntelliSense:

Example of IntelliSense on HTML div element after the type has been declared.

Related