Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode IntelliSense does not autocomplete JavaScript DOM events and methods

I am using Visual Studio Code version 1.17.1.

In *.js file when I type document.querySelector("#elementId").style. I have no IntelliSense hints for styles (like margin, display, etc.). Even no onclick event hint after document.querySelector("#elementId").

enter image description here

enter image description here

I don't use any npm packages. It is just simple html\css\js project.

How to turn on correct IntelliSense hints? Thanks.

like image 375
Stanislav Avatar asked Oct 17 '17 18:10

Stanislav


People also ask

Why is my autocomplete not working in VS Code?

Why is VS Code suggestions not working? If you're coding in JavaScript or TypeScript and finds that VSCode IntelliSense does work but does not behave properly, it's likely that you've selected the wrong language mode. TypeScript and JavaScript share the same language service, so you need to select the right language.

How do I enable autocomplete in VS Code?

PS: Pressing "Enter" works fine and accepts the suggestion and I can disable it by setting the following setting to off. Don't know if this helps, but you can press CTRL+SPACE to bring up autocomplete.

Why is IntelliSense not working Visual Studio 2022?

Please try: Go to Visual Studio Installer, click Modify , uncheck IntelliCode in Individual components, then click Modify button to save the change, wait for the installation to complete, and then reinstall IntelliCode . In Visual Studio, go to Tools->Options->IntelliCode to check if the setting is Default.


1 Answers

Because result of the querySelector is either:

Element - the most general base class or null

If you already know id you can use document.getElementById() - which returns instance of more specific class - HTMLElement - autocomplete will work as expected.

document.getElementById('elementId').

If you don't know id, but want autocomplete you can use JSDoc type annotations:

/** @type {HTMLElement} */
var el =  document.querySelector(".myclass");

el.

// or without extra variable:
/** @type {HTMLElement} */
(document.querySelector(".myclass")).

I haven't really tested it but you can try something like that:

/**
 * @type {function(string): HTMLElement}
 */
var querySelector = document.querySelector.bind(document);

querySelector('.myclass').

Another choice would be alter typescript types:

  1. Create file dom.d.ts
  2. Append to it:
interface NodeSelector {
    querySelector<K extends keyof ElementTagNameMap>(selectors: K): ElementTagNameMap[K] | null;
    querySelector<E extends HTMLElement = HTMLElement>(selectors: string): E | null;
    querySelectorAll<K extends keyof ElementListTagNameMap>(selectors: K): ElementListTagNameMap[K];
    querySelectorAll<E extends HTMLElement = HTMLElement>(selectors: string): NodeListOf<E>;
}

Now querySelector returns HTMLElement.

like image 123
Alex Avatar answered Oct 21 '22 09:10

Alex